Python-matplotlib 堆积柱状图绘制

2021-02-22 15:11:49 浏览数 (1)

01. 引言

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

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

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

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

代码语言:javascript复制
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:DataCharmSCI paper plotssci_bar_guanwang',width=5,height=3,
            dpi=900,bbox_inches='tight')
plt.show()

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

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

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

代码语言:javascript复制
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')
ax.bar(label, ma_number, width,  bottom=mu_number, label='Math')
ax.bar(label, en_number, width,  bottom=ma_number, label='English')
ax.bar(label, ch_number, width,  bottom=en_number, label='Chinese')
ax.legend()
ax.set_ylabel('Numbers of Studies')
ax.set_xlabel('Time(year)')
text_font = {'size':'14','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:DataCharmSCI paper plotssci_bar.png',width=5,height=3,
            dpi=900,bbox_inches='tight')

结果如下:

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

03. 可视化定制化设计

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

代码语言:javascript复制
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:DataCharmSCI paper plotssci_bar_04.png',width=5,height=3,
            dpi=900,bbox_inches='tight')

结果如下:

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

代码语言:javascript复制
for spine in ['bottom','left']:
    ax.spines[spine].set_linewidth(1.5)
    
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

结果如下:

04. 总结

堆积柱状图算是柱状图中较多出现的图表,本期推文也算是对其进行简单的讲解了,加上此类图表,我想在对柱状图的绘制应该有所了解了

0 人点赞