python - 对 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
解决方案
df1-df4
想法是使用by创建一个 Dataframe concat
,仅在列表理解中将Finish
列转换为数字,并且还通过索引。Series.str.extract
Season
DataFrame.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()
推荐阅读
- jquery - Github 将多个文件合并为单个压缩主文件
- javascript - 如何在垂直标签内容框的div内显示d3js图表?
- c++ - 检查模板参数是否“可调用”的 C++11 方法
- ignite - 点燃丢失的桌子
- java - 什么时候实现WebMvcConfigurer来配置Spring MVC?
- asp.net - 在 ASP.NET Webapp 中启用 Windows 身份验证
- python - 比较 2 个列表的元素并仅打印不同的元素
- xamarin - 带有自定义导航的 WebView 没有出现在 Xamarin 表单中
- python - 如何将环境变量从 .env 文件传递给 supervisord
- regex - 如何使用 sed 命令删除短语后的数字和日期时间?