Python可视化:matplotlib 绘制堆积柱状图绘制
发布日期:2021-05-17 02:07:27 浏览次数:20 分类:精选文章

本文共 1929 字,大约阅读时间需要 6 分钟。

题目: Matplotlib 堆积柱状图绘制及典型应用

引言

查找资料时了解到堆积柱状图是一种直观易懂的数据可视化形式,不仅绘制也相对简单。本人决定通过构建虚拟数据和Matplotlib绘制示例,详细步骤如下:

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

根据柱状图特点,构建的虚拟数据如下。通过简单的Matplotlib代码实现堆积柱状图绘制。

代码展示:HTML

import matplotlib.pyplot as plt
import pandas as pd
# 假设bar_data为数据框,包含以下列: music, math, english, chinese
label = 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 = 0.35 # 各柱宽度
plt.rcParams['font.family'] = "Times New Roman"
# 创建柱状图
ax = plt.bar(label, mu_number, width=width, label='Music', color='white', hatch='//')
ax.bar(label, ma_number, width=width, bottom=mu_number, label='Math', color='gray',
ec='k', lw=0.6)
ax.bar(label, en_number, width=width, bottom=ma_number, label='English', color='white',
hatch='...', ec='k', lw=0.6)
ax.bar(label, ch_number, width=width, bottom=en_number, label='Chinese', color='white',
hatch='\\', ec='k', lw=0.6)
# 设置图表样式
plt.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('Number 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', dpi=900, bbox_inches='tight')
plt.show()

注意:由于涉及到文件路径和图片保存,直接复制使用可能导致问题,请根据实际路径调整。

堆积柱状图效果:

图1:基础堆积柱状图示例

图2:调整颜色与填充的堆积柱状图

图3:对轴线进行细化的堆积柱状图

图4:论文标准的堆积柱状图呈现

文章来源于网络,仅供学习、交流使用,版权归原作者所有。本文主要介绍了堆积柱状图的基础用法及实际应用案例,对开发电子技能感兴趣的小伙伴可以参考学习。

上一篇:Python爬虫练习:去爬某平台音乐
下一篇:Python基础动画绘制,图案、样式、运动轨迹随你定

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2025年05月02日 14时00分42秒