python做柱状图的数据可视化_python柱状图代码

python做柱状图的数据可视化_python柱状图代码在 Python 中 使用 matplotlib pyplot 模块可以创建柱状图 并通过 plt text 方法在柱子上显示数据 以下是一个简单的示例代码 展示了如何在柱状图上显示数据 pythonimport matplotlib pyplot as plt 创建数据 data 1 2 3 4 创建柱状图 plt bar range len data

在Python中,使用 `matplotlib.pyplot` 模块可以创建柱状图,并通过 `plt.text()` 方法在柱子上显示数据。以下是一个简单的示例代码,展示了如何在柱状图上显示数据:

 import matplotlib.pyplot as plt 创建数据 data = [1, 2, 3, 4] 创建柱状图 plt.bar(range(len(data)), data) 在柱子上显示数据 for i, v in enumerate(data): plt.text(i, v + 0.1, str(v), ha='center', va='bottom') 设置图表标题和坐标轴标签 plt.title('Bar Chart with Data Labels') plt.xlabel('Index') plt.ylabel('Value') 显示图表 plt.show() 

这段代码首先创建了一个简单的柱状图,然后通过循环遍历数据列表,在每一个柱子上添加文本标签来显示对应的数值。`ha='center'` 表示文本水平居中,`va='bottom'` 表示文本垂直方向在柱子的底部。

如果你需要显示的是多个数据系列的柱状图,并且想要为每个系列分别设置填充颜色,可以像下面这样修改代码:

 import matplotlib.pyplot as plt 创建数据 data1 = [68, 96, 85, 86, 76, 87, 95] data2 = [85, 68, 79, 89, 94, 82, 90] names = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] 创建柱状图 width = 0.35 柱形之间的宽度 x = range(len(names)) fig, ax = plt.subplots() bar1 = ax.bar(x, data1, width, label='Math', fc='blue') bar2 = ax.bar(x, data2, width, label='Science', fc='red') 在柱子上显示数据 for bar in bar1: height = bar.get_height() ax.text(bar.get_x() + bar.get_width() / 2, height, '%.2f' % float(height), ha='center', va='bottom') for bar in bar2: height = bar.get_height() ax.text(bar.get_x() + bar.get_width() / 2, height, '%.2f' % float(height), ha='center', va='bottom') 设置图表标题和坐标轴标签 ax.set_title('Bar Chart with Data Labels') ax.set_xlabel('Category') ax.set_ylabel('Score') ax.set_xticks(x) ax.set_xticklabels(names) ax.legend() 显示图表 plt.show() 

在这个示例中,我们创建了两个不同颜色的数据系列柱状图,并且为每个柱子上添加了文本标签显示数值。

编程小号
上一篇 2025-03-06 13:23
下一篇 2025-03-06 13:20

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/117598.html