首页  >  文章  >  后端开发  >  如何在 Matplotlib 中用每个条形的多个值注释分组条形图?

如何在 Matplotlib 中用每个条形的多个值注释分组条形图?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 10:24:30638浏览

How to annotate a grouped bar chart in Matplotlib with multiple values for each bar?

分组条形图的多个注释

问题:
尝试使用 Matplotlib 创建分组条形图时,输出显示不正确.

代码示例:

<code class="python">import matplotlib.pyplot as plt

# sample data
labels = ['Label 1', 'Label 2', 'Label 3']
data1 = [5, 10, 15]
data2 = [15, 10, 5]

# create the bar chart
plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

# attempt to annotate each bar
for i in range(3):
    plt.annotate(data1[i], (labels[i], data1[i]), xytext=(-5, 5), textcoords='offset points')
    plt.annotate(data2[i], (labels[i], data2[i]+data1[i]), xytext=(-5, 5), textcoords='offset points')

plt.legend()
plt.show()</code>

预期输出:

每个条形都应标注其各自的值。

解决方法:

方法一:使用bar_label

<code class="python">import matplotlib.pyplot as plt

plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

for i in range(3):
    plt.bar_label(plt.gca().containers[i], labels=(data1[i], data2[i]), fmt='%.1f', padding=10)

plt.legend()
plt.show()</code>

方法二:使用annotate

<code class="python">import matplotlib.pyplot as plt

plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

for i in range(3):
    height1 = data1[i]
    height2 = data2[i]

    # annotate for data set 1
    plt.annotate(str(height1), (labels[i], height1), xytext=(0, 5), textcoords='offset points')

    # annotate for data set 2
    plt.annotate(str(height2), (labels[i], height1 + height2), xytext=(0, 5), textcoords='offset points')

plt.legend()
plt.show()
````
</code>

以上是如何在 Matplotlib 中用每个条形的多个值注释分组条形图?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn