在Python中,使用matplotlib库可以很容易地绘制柱形图并在柱形上显示数值。以下是一个简单的示例代码,展示了如何绘制柱形图并在柱形上添加数值标签:
import matplotlib.pyplot as plt
定义数据
categories = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
values = [68, 96, 85, 86, 76, 87, 95]
绘制柱形图
plt.bar(categories, values)
定义一个函数来自动添加数值标签
def autolabel(bars):
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width() / 2, height, '%.2f' % float(height), ha='center', va='bottom')
自动添加数值标签
autolabel(plt.gca().patches)
设置图表标题和坐标轴标签
plt.title('Bar Chart with Values')
plt.xlabel('Categories')
plt.ylabel('Values')
显示图表
plt.show()
这段代码首先导入了matplotlib.pyplot模块,然后定义了要绘制的柱形图的数据。使用`plt.bar()`函数绘制柱形图,并通过定义的`autolabel`函数在每根柱子上添加数值标签。最后,设置了图表的标题和坐标轴标签,并使用`plt.show()`显示图表。
如果你需要进一步自定义图表的样式,比如设置中文字体,可以添加以下代码:
plt.rcParams['font.sans-serif'] = ['SimHei'] 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False 用来正常显示负号
这样就可以在图表中正常显示中文字符了