Python可视化:matplotlib 绘制堆积柱状图绘制

引言

在查找资料时看到了堆积柱状图,简单明了,而且绘制起来也不是很难,再结合自己的教程推文中也确实没有此类图表,即决定通过构建虚拟数据进行matplotlib堆积柱状图的绘制推文,详细内容如下:

PS:如有需要Python学习资料的小伙伴可以加下方的群去找免费管理员领取

 

可以免费领取源码项目实战视频PDF文件

 

数据构建及默认可视化设置

结合此类图表特点,我们构建的数据结果如下:

 

在matplotlib中要想绘制堆积柱状图,则需要灵活设置 ax.bar()绘图函数中bottom参数,先看一下简单的例子:

import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
width = 0.35       # the width of the bars: can also be len(x) sequence
fig, ax = plt.subplots(figsize=(5,3),dpi=200)
ax.bar(labels, men_means, width,label='Men')
ax.bar(labels, women_means, width, bottom=men_means,label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.legend()
ax.text(.87,-.08,'\nVisualization by DataCharm',transform = ax.transAxes,
        ha='center', va='center',fontsize = 5,color='black',fontweight='bold',family='Roboto Mono')
plt.savefig(r'F:\DataCharm\SCI paper plots\sci_bar_guanwang',width=5,height=3,
            dpi=900,bbox_inches='tight')
plt.show()

这里women 柱状图时,bottom设置为 men_means ,结果如下:

 

看到这里,对柱状图的堆积应该有了一个较好的理解了吧

回到我们虚构的数据,使用默认的matplotlib参数,代码如下:

plt.rcParams['font.family'] = "Times New Roman"
fig,ax = plt.subplots(figsize=(8,5),dpi=200)

label = [i for i in bar_data.columns[1:]]
mu_number = bar_data.iloc[0,1:].values
ma_number = bar_data.iloc[1,1:].values
en_number = bar_data.iloc[2,1:].values
ch_number = bar_data.iloc[3,1:].values

width = .4

ax.bar(label, mu_number, width, label='Music',color='white',hatch="//",ec='k',lw=.6)
ax.bar(label, ma_number, width,  bottom=mu_number, label='Math',color='gray',ec='k',lw=.6)
ax.bar(label, en_number, width,  bottom=ma_number, label='English',color='white',hatch="...",ec='k',lw=.6)
ax.bar(label, ch_number, width,  bottom=en_number, label='Chinese',color='white',hatch="\\\\",ec='k',lw=.6)
ax.set_ylim(0,120)
ax.tick_params(direction='out',labelsize=12,length=5.5,width=1,top=False,right=False)
ax.legend(fontsize=11,frameon=False,loc='upper center',ncol=4)
ax.set_ylabel('Numbers of Studies',fontsize=13)
ax.set_xlabel('Time(year)',fontsize=13)
text_font = {'size':'17','weight':'bold','color':'black'}
ax.text(.03,.93,"(a)",transform = ax.transAxes,fontdict=text_font,zorder=4)
ax.text(.87,-.08,'\nVisualization by DataCharm',transform = ax.transAxes,
        ha='center', va='center',fontsize = 5,color='black',fontweight='bold',family='Roboto Mono')
plt.savefig(r'F:\DataCharm\SCI paper plots\sci_bar_04.png',width=5,height=3,
            dpi=900,bbox_inches='tight')

结果如下:

 

虽然效果也还不错,但想要达到出版的要求,可能还需要进行定制化需求设置。

可视化定制化设计

要想 达到一般出版社的要求,对其颜色、填充、刻度、轴脊、字体等都需要自行设置,具体代码如下:

plt.rcParams['font.family'] = "Times New Roman"
fig,ax = plt.subplots(figsize=(8,5),dpi=200)

label = [i for i in bar_data.columns[1:]]
mu_number = bar_data.iloc[0,1:].values
ma_number = bar_data.iloc[1,1:].values
en_number = bar_data.iloc[2,1:].values
ch_number = bar_data.iloc[3,1:].values

width = .4

ax.bar(label, mu_number, width, label='Music',color='white',hatch="//",ec='k',lw=.6)
ax.bar(label, ma_number, width,  bottom=mu_number, label='Math',color='gray',ec='k',lw=.6)
ax.bar(label, en_number, width,  bottom=ma_number, label='English',color='white',hatch="...",ec='k',lw=.6)
ax.bar(label, ch_number, width,  bottom=en_number, label='Chinese',color='white',hatch="\\\\",ec='k',lw=.6)
ax.set_ylim(0,120)
ax.tick_params(direction='out',labelsize=12,length=5.5,width=1,top=False,right=False)
ax.legend(fontsize=11,frameon=False,loc='upper center',ncol=4)
ax.set_ylabel('Numbers of Studies',fontsize=13)
ax.set_xlabel('Time(year)',fontsize=13)
text_font = {'size':'17','weight':'bold','color':'black'}
ax.text(.03,.93,"(a)",transform = ax.transAxes,fontdict=text_font,zorder=4)
ax.text(.87,-.08,'\nVisualization by DataCharm',transform = ax.transAxes,
        ha='center', va='center',fontsize = 5,color='black',fontweight='bold',family='Roboto Mono')
plt.savefig(r'F:\DataCharm\SCI paper plots\sci_bar_04.png',width=5,height=3,
            dpi=900,bbox_inches='tight')

结果如下:

有的时候对轴脊的设置也有很严的要求,通过添加如下代码,即可对轴脊进行设置:

for spine in ['bottom','left']:
    ax.spines[spine].set_linewidth(1.5)
    
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

结果如下:

 

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

以上文章来源于DataCharm,作者宁海涛

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页