Matplotlib 如何在柱状图上显示数值
Matplotlib是一个Python的数据可视化库,在数据分析和数据可视化领域广受欢迎。其中,柱状图是一种常用的可视化方式,可以用于展示不同类别或时间段的数据变化情况。在柱状图中,为了更清晰地展现数据,通常需要在柱子的顶部加上具体数值,本文将介绍两种在Matplotlib中实现这个功能的方法。
阅读更多:Matplotlib 教程
方法一:使用annotate函数
Matplotlib中的annotate函数可以用于在图形上添加文本注释,可以用来在柱子顶部添加数值。具体步骤如下:
- 在绘制柱状图时,需要记录每个柱子的高度,用于后续数值的定位。可以使用heights变量保存每个柱子的高度,如下所示:
import matplotlib.pyplot as plt x = ['A', 'B', 'C', 'D'] y = [10, 20, 30, 40] fig, ax = plt.subplots() rects = ax.bar(x, y) heights = [] for rect in rects: height = rect.get_height() heights.append(height)
- 使用for循环遍历高度列表,为每个柱子添加数值。annotate函数的参数中,第一个参数是文本内容,第二个参数xy是文本的坐标位置,第三个参数xytext是文本的偏移量,使用ha和va参数可以指定文本的对齐方式,如下所示:
for i, rect in enumerate(rects): plt.annotate('{:.0f}'.format(y[i]), xy=(rect.get_x() + rect.get_width() / 2, heights[i]), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom')
annotate函数会在每个柱子的顶部添加数值,该数值为y中对应位置的值,并使用format函数保留整数位。
完整代码如下所示:
import matplotlib.pyplot as plt x = ['A', 'B', 'C', 'D'] y = [10, 20, 30, 40] fig, ax = plt.subplots() rects = ax.bar(x, y) heights = [] for rect in rects: height = rect.get_height() heights.append(height) for i, rect in enumerate(rects): plt.annotate('{:.0f}'.format(y[i]), xy=(rect.get_x() + rect.get_width() / 2, heights[i]), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') plt.show()
方法二:使用text函数
除了annotate函数外,Matplotlib中的text函数也可以用于在图形上添加文本。同样可以用来在柱子顶部添加数值。具体步骤如下:
- 在绘制柱状图时,需要记录每个柱子的高度,用于后续数值的定位。可以使用heights变量保存每个柱子的高度,如下所示:
import matplotlib.pyplot as plt x = ['A', 'B', 'C', 'D'] y = [10, 20, 30, 40] fig, ax = plt.subplots() rects = ax.bar(x, y) heights = [] for rect in rects: height = rect.get_height() heights.append(height)
- 使用for循环遍历高度列表,为每个柱子添加数值。text函数的前两个参数与annotate函数相同,分别指定文本内容和文本坐标位置,使用va参数可以指定文本的垂直对齐方式,如下所示:
for i, rect in enumerate(rects): plt.text(rect.get_x() + rect.get_width() / 2, heights[i], '{:.0f}'.format(y[i]), ha='center', va='bottom')
text函数会在每个柱子的顶部添加数值,该数值为y中对应位置的值,并使用format函数保留整数位。
完整代码如下所示:
import matplotlib.pyplot as plt x = ['A', 'B', 'C', 'D'] y = [10, 20, 30, 40] fig, ax = plt.subplots() rects = ax.bar(x, y) heights = [] for rect in rects: height = rect.get_height() heights.append(height) for i, rect in enumerate(rects): plt.text(rect.get_x() + rect.get_width() / 2, heights[i], '{:.0f}'.format(y[i]), ha='center', va='bottom') plt.show()
运行结果与方法一相同,不再展示。
总结
通过本文,我们介绍了在Matplotlib中如何在柱状图上显示数值,其中使用annotate函数和text函数各有特点,可以根据实际情况选择合适的方法进行实现。希望本文能够帮助到数据分析和数据可视化领域的从业人员,也欢迎大家在实践中探索更多有趣的可视化方式。