python 对10行7列数据做堆叠柱状图,并加上数字标签,标签位置在每个色块上
时间: 2024-09-26 09:14:28 浏览: 40
Python 中可以使用 matplotlib 库来创建堆叠柱状图,例如 `pyplot` 或者 `seaborn` 库,下面是使用 `matplotlib` 的简单示例:
```python
import matplotlib.pyplot as plt
# 假设我们有10行7列的数据,存储在一个二维数组中
data = [[random.randint(0, 10) for _ in range(7)] for _ in range(10)]
# 创建一个新的 figure 和 axes
fig, ax = plt.subplots()
# 创建堆叠柱状图,x轴表示行索引,y轴表示值
ax.bar(range(10), data[0], label='Stacked bar 1', bottom=0)
for i in range(1, len(data)):
ax.bar(range(10), data[i], label=f'Stacked bar {i+1}', bottom=data[:i].sum(axis=0))
# 添加数字标签到每个色块上
for index, value in enumerate(ax.patches):
# 获取条形的高度
height = value.get_height()
# 设置文本的位置在顶部中央
ax.text(index, height + 0.5, f'{int(height)}', ha='center', va='bottom')
# 设置标题、坐标轴标签以及图例
ax.set_title('Stacked Bar Chart with Numerical Labels')
ax.set_xlabel('Rows')
ax.set_ylabel('Values')
ax.legend(title='Stacked Bars')
# 显示图形
plt.show()
阅读全文
相关推荐


















