pandas的分组对比柱状图
先说下思路
- 原表是有两列需要对比的数据,number和number2
- 排序,按照number2进行排序sort_values
- 关键的在于将两个对比的数据plt.bar写成list就可以
- 在做一些样式的调整
import pandas as pd
import matplotlib.pyplot as plt
students = pd.read_excel('D:/Pandas/Various.xlsx')
# 按照number排序,然后从大到小排序
students.sort_values(by='Number2', inplace=True, ascending=False)
# 一个横坐标一个纵坐标,还有颜色的 设置柱状图颜色
students.plot.bar(x='Field' ,y=['Number1','Number2'], color=['grey','orange'])
# rotation的值只有horizontal,和vertical,90是不行的,就是一个纵排一个横排
ax = plt.gca()
ax.set_xticklabels(students['Field'],rotation=45,ha = 'right')
# 设置横坐标和纵坐标的标题
plt.xlabel('Filed',fontweight ='bold')
plt.ylabel('Number',fontweight ='bold')
plt.title('International Students by Field',fontsize= '16',fontweight ='bold')
# 设置图表移动
f = plt.gcf()
f.subplots_adjust(left=0.2,bottom=0.42)
plt.show()
结果:
写代码的时候不明白
set_xticklabels和subplots_adjust不能关联出来。这么长还不能关联。