使用Python实现嵌套绘图并为条形图添加自定义标注
程序人生路
2024-04-02 17:21
短信预约 Python-IT技能 免费直播动态提醒
这篇文章将为大家详细讲解有关使用Python实现嵌套绘图并为条形图添加自定义标注,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
导入库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
准备数据
# 创建数据框
df = pd.DataFrame({
"班级": ["A", "B", "C"],
"数学": [80, 90, 70],
"英语": [85, 80, 95],
"科学": [90, 75, 85]
})
嵌套绘图
要创建嵌套绘图,首先需要创建一个主图,然后将子图添加到主图中。
# 创建主图
fig, ax = plt.subplots()
# 添加子图
ax_math = ax.bar(df["班级"], df["数学"], color="blue")
ax_english = ax.bar(df["班级"], df["英语"], color="red", bottom=df["数学"])
ax_science = ax.bar(df["班级"], df["科学"], color="green", bottom=df["数学"]+df["英语"])
自定义标注
为了添加自定义标注,可以使用 matplotlib.text
函数。
# 为每个条形图添加文本标注
for bar in ax_math:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height, f"{int(height)}", ha="center", va="bottom")
for bar in ax_english:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height, f"{int(height)}", ha="center", va="bottom")
for bar in ax_science:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height, f"{int(height)}", ha="center", va="bottom")
图例
# 添加图例
plt.legend((ax_math[0], ax_english[0], ax_science[0]), ("数学", "英语", "科学"))
显示图表
plt.show()
完整代码:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"班级": ["A", "B", "C"],
"数学": [80, 90, 70],
"英语": [85, 80, 95],
"科学": [90, 75, 85]
})
fig, ax = plt.subplots()
ax_math = ax.bar(df["班级"], df["数学"], color="blue")
ax_english = ax.bar(df["班级"], df["英语"], color="red", bottom=df["数学"])
ax_science = ax.bar(df["班级"], df["科学"], color="green", bottom=df["数学"]+df["英语"])
for bar in ax_math:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height, f"{int(height)}", ha="center", va="bottom")
for bar in ax_english:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height, f"{int(height)}", ha="center", va="bottom")
for bar in ax_science:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height, f"{int(height)}", ha="center", va="bottom")
plt.legend((ax_math[0], ax_english[0], ax_science[0]), ("数学", "英语", "科学"))
plt.show()
以上就是使用Python实现嵌套绘图并为条形图添加自定义标注的详细内容,更多请关注编程学习网其它相关文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341