問題:
嘗試使用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>
方法🎜 >
以上是如何在 Matplotlib 中用每個長條的多個值註解分組長條圖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!