Python 绘画excel分组柱状图(懒人学习)

1.excel案例如截图:

很简单大家自己照着做一个就可以了。
Python 绘画excel分组柱状图(懒人学习)_第1张图片

2.完整代码如下:

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’)

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()


3、代码解释

3.1引入库

代码如下(示例):

import pandas as pd
import matplotlib.pyplot as plt

引入pandas,matplotlib库,没有的话自己安装一个。

3.2读入数据

代码如下(示例):

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轴数据,颜色对应橘黄色和红色。


3.3画图

代码如下(示例):

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:`图示

Python 绘画excel分组柱状图(懒人学习)_第2张图片

2.数据。
Python 绘画excel分组柱状图(懒人学习)_第3张图片

你可能感兴趣的:(python,学习,pandas)