Python实现条形图的绘制

Python实现条形图的绘制:

说明:代码运行环境:Win10+Python3+jupyter notebook

条形图是一种用来描绘已汇总的分类型数据的频数分布、相对频数分布或百分数频数分布。(百分数频数就是相对频数乘以100%)

方法1:pandas中的Series对象或者DataFrame对象调用plot()或plot.bar()、plot.barh()方法;

Series.plot()用法:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.html#pandas.Series.plot

DataFrame.plot()的用法:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html

Series.plot.bar()的用法:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.plot.bar.html#pandas.Series.plot.bar

DataFrame.plot.bar()的用法:

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html

具体示例:

导出要用到的相关包:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

Series.plot.bar()示例:

fig,axes = plt.subplots(2,1)
data = pd.Series(np.random.rand(16),index=list('abcdefghijklmnop'))
data.plot.bar(ax=axes[0],color='k',alpha=0.7,rot=0)
data.plot.barh(ax=axes[1],color='k',alpha=0.7)
plt.savefig('p4.png')

上述代码的输出结果是:

采用axes[].set_······()方法对子图中的各种元素进行设置。

具体参见官方文档:

https://matplotlib.org/api/axes_api.html?highlight=axes#module-matplotlib.axes

如何调整上图中第二个子图纵轴上标签之间的间距?

解决方法是将增大figure的尺寸,可以手动调整,也可以通过代码调整。

DataFrame.plot.bar()示例:

# 创建一个DataFrame对象
df = pd.DataFrame(np.random.rand(6,4),
                 index=['one','two','three','four','five','six'],
                 columns=pd.Index(['A','B','C','D'],name='Genus'))


fig,axes = plt.subplots(1,1)
df.plot.bar(ax=axes,stacked=True,alpha=0.7,rot=0)  # stacked=True时绘制的是堆积条形图
axes.set_title('The first bar plot')                
plt.savefig('p5.png')

 # bar绘制的垂直方向的条形图,barh绘制的是水平的条形图

上述代码的输出结果为:

同理,上图中的各个元素可以通过调用axes.set_······()来设置。

如果上述代码中的df.plot.bar改为df.plot.barh则原条形图变为:

方法2:从seaborn包中调用barplot()方法。

具体示例:

seaborn.barplot()示例:

data = {'state':['Ohio','Nevada','Ohio','Nevada'],
       'year':[2000,2000,2001,2001],
       'pop':[1.5,1.7,1.8,2.5]}
frame = pd.DataFrame(data)
fig,axes = plt.subplots(2,1)
sns.barplot(x='state',y='pop',hue='year',data=frame,ax=axes[0],orient='v')
sns.barplot(x='pop',y='state',hue='year',data=frame,ax=axes[1],orient='h')
plt.savefig('p7.png')

#当要绘制水平方向的条形图时注意要交换x与y所表示的值

上述代码地输出结果是:

同理,上图中的各个元素可以通过调用axes[].set_······()来设置。

如何调整上图中各个subplot之间的间距?

可以使用pyplot.subplots_adjust()方法调整,具体可参见官方文档:

https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html?highlight=subplots_adjust#matplotlib.pyplot.subplots_adjust

参考资料:

《利用Python进行数据分析》第二版

《商务与经济统计》第十三版

matplotlib、seaborn、pandas官方文档

PS1:打算写一个Python实现常用图表的系列,这个系列所采用的绘图方式是通过subplot的示例来调用绘制各种图形的方法,我把它理解成面对对象式绘图,与此相对的是函数式绘图,通过matplotlib.pyplot来调用绘制各种图形的函数。

PS2:本文是博主的第一篇博客,难免有疏漏之处,欢迎交流讨论

猜你喜欢

转载自blog.csdn.net/qq_41080850/article/details/83757616
今日推荐