import pandas as pd
import matplotlib.pyplot as plt
students = pd.read_excel(‘H:/Python自动化办公–Pandas玩转Excel源代码(7-30)/010/Students.xlsx’)
students.sort_values(by=‘2017’, inplace=True, ascending=False)
print(students)
students.plot.bar(‘Field’, [‘2016’, ‘2017’], color=[‘orange’, ‘Red’])
plt.title(‘International Students by Field’, fontsize=16)
plt.xlabel(‘Field’, fontweight=‘bold’)
plt.ylabel(‘Number’, fontweight=‘bold’)
ax = plt.gca()
ax.set_xticklabels(students[‘Field’], rotation=40, ha=‘right’)
plt.gcf().subplots_adjust(left=0.2, bottom=0.42)
plt.show()
代码如下(示例):
import pandas as pd
import matplotlib.pyplot as plt
引入pandas,matplotlib库,没有的话自己安装一个。
代码如下(示例):
students = pd.read_excel('H:/Python自动化办公--Pandas玩转Excel源代码(7-30)/010/Students.xlsx')
students.sort_values(by='2017', inplace=True, ascending=False)
print(students)
students.plot.bar('Field', ['2016', '2017'], color=['orange', 'Red'])
1.'H:/Python自动化办公–Pandas玩转Excel源代码(7-30)/010/Students.xlsx’读取这个路径的文件,路径你们自己改,放在那里就填写哪里。
2.students.sort_values(by=‘2017’, inplace=True, ascending=False)其中:ascending:默认为True升序排序,为False降序排序。
inplace:是否修改原始Series。
by=2017 这一列的字符串。 这一行的意思就是将2017列的数据进行降序排序。
3.print(students)打印出来
4.students.plot.bar(‘Field’, [‘2016’, ‘2017’], color=[‘orange’, ‘Red’])其中:Field为X轴,2016,2017为y轴数据,颜色对应橘黄色和红色。
代码如下(示例):
plt.title('International Students by Field', fontsize=16)
plt.xlabel('Field', fontweight='bold')
plt.ylabel('Number', fontweight='bold')
# plt.tight_layout()
ax = plt.gca()
ax.set_xticklabels(students['Field'], rotation=40, ha='right')
plt.gcf().subplots_adjust(left=0.2, bottom=0.42)
plt.show()
1.plt.title(‘International Students by Field’, fontsize=16) 标题内容,尺寸16。
2.plt.xlabel(‘Field’, fontweight=‘bold’) x轴Field字体加粗。
3.plt.ylabel(‘Number’, fontweight=‘bold’) y轴Number字体加粗。
4.ax = plt.gca()旋转一下x标签,让它少占空间。ax.set_xticklabels(students[‘Field’], rotation=40, ha=‘right’)设置x轴文字。
此处 ha='right’点在注释右边,rotation=40旋转40°。
5.plt.gcf().subplots_adjust(left=0.2, bottom=0.42)其中有六个可选参数来控制子图布局。值均为0~1之间。其中left、bottom、right、top围成的区域就是子图的区域。wspace、hspace分别表示子图之间左右、上下的间距。实际的默认值由matplotlibrc文件控制的。0.2距离左边,0.42距离顶边。
6.plt.show()这个还用我说。。
1:`图示