首页 > 解决方案 > 对 Y 轴值进行排序

问题描述

我正在绘制 4 支球队的赛季与完成位置,但 y 轴是由代码随机绘制的,而不是根据位置排序的。有什么办法解决这个问题?这是我的代码

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

将 pandas 导入为 pd,将 numpy 导入为 np,将 matplotlib 导入为 mpl,将 matplotlib.pyplot 导入为 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

标签: pythonpandasnumpymatplotlib

解决方案


df1-df4想法是使用by创建一个 Dataframe concat,仅在列表理解中将Finish列转换为数字,并且还通过索引。Series.str.extractSeasonDataFrame.set_index

最后的情节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()

推荐阅读