问题:
尝试使用 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中文网其他相关文章!