2
votes

I'm plotting Season vs Finish position of 4 teams but the y-axis is plotted randomly by the code and not sorted according to the position. What's the fix for this? this is my code

Sample data:
   Season Finish - df1
0    1950    4th
1    1951    3rd
2    1952    4th
3    1953    3rd
4    1954    3rd
   Season Finish - df2
0    1950    4th
1    1951    2nd
2    1952    1st
3    1953    1st
4    1954    1st
   Season Finish - df3
0    1950    1st
1    1951    1st
2    1952    1st
3    1953    1st
4    1954    1st
   Season Finish - df4
0    1950    2nd
1    1951    5th
2    1952    8th
3    1953    6th
4    1954    5th

import pandas as pd, import numpy as np, import matplotlib as mpl, import matplotlib.pyplot as plt,

df1 = pd.read_csv('Pistons.csv')
df2 = pd.read_csv('lions.csv')
df3 = pd.read_csv('red-wings.csv')
df4 = pd.read_csv('Tigers.csv')

df_list = [df1, df2, df3, df4]

for i in df_list:
    #     i['Season'] = i['NFL season']
    i.rename(columns={i.columns[0]: "Season"}, inplace=True)

# print(df1['Season'])

# change name of to season
# for i in df_list:
#     plt.plot(i.Season, i.Finish,)

plt.plot(df1.Season, df1.Finish, label="Pistons")
plt.plot(df2.Season, df2.Finish, label="Lions")
plt.plot(df3.Season, df3.Finish, label="Red Wings")
plt.plot(df4.Season, df4.Finish, label="Tigers")

plt.gca().invert_yaxis()
plt.title("Season vs Finish Position Graph", fontsize=17)
plt.xlabel('Season (Year)', fontsize=13)
plt.ylabel('Finish Position', fontsize=13)
plt.legend(loc=4, fontsize=10, frameon=False)
plt.show()


[Image of the output here][1].stack.imgur.com/POmXR.png
1
Can you add sample data? print (df1[['Season',''Finish]]), print (df2[['Season',''Finish]]), print (df3[['Season',''Finish]]), print (df4[['Season',''Finish]]) ? - jezrael

1 Answers

1
votes

Idea is create one Dataframe with df1-df4 by concat, only convert Finish column to numbers by Series.str.extract in list comprehension and also Season to index by DataFrame.set_index.

Last plot by DataFrame.plot:

names = ['Pistons','Lions','Red Wings','Tigers']
df_list = [df1, df2, df3, df4]

new = [x.set_index('Season')['Finish'].str.extract('(\d+)', expand=False).astype(int) 
                                                                         for x in df_list]
df = pd.concat(new, axis=1, keys=names)
print (df)
        Pistons  Lions  Red Wings  Tigers
Season                                   
1950          4      4          1       2
1951          3      2          1       5
1952          4      1          1       8
1953          3      1          1       6
1954          3      1          1       5

df.plot()

plt.gca().invert_yaxis()
plt.title("Season vs Finish Position Graph", fontsize=17)
plt.xlabel('Season (Year)', fontsize=13)
plt.ylabel('Finish Position', fontsize=13)
plt.legend(loc=4, fontsize=10, frameon=False)
plt.show()