這個問題在這里已經有了答案:
該圖表由 2 個不同的陣列組成:
[' A6' ' Q2' ' Q5' ' A5' ' A1' ' A4' ' Q3' ' A3']
[ 748 822 877 882 1347 1381 1417 1929]
第一個是我相信的字串陣列。現在,我查找了不同的解決方案來注釋條形圖,我能找到的每個解決方案都帶有 Pandas 資料框圖。我的有 numpy 陣列......我不知道這是否應該使它更復雜?
無論如何,這是我試圖在圖表上獲取注釋的代碼:
plt.figure()
plot = plt.bar(x, y)
for bar in plot.patches:
plot.annotate(bar.get_height(),
(bar.get_x() bar.get_width() / 2,
bar.get_height()), ha='center', va='center',
size=15, xytext=(0, 8),
textcoords='offset points')
plt.xlabel("Car Model")
plt.ylabel("Car Frequency")
plt.title("Frequency of Most Popular Audi Cars")
plt.ylim(bottom=0)
plt.show()
這段代碼給了我一個錯誤:
Traceback (most recent call last):
File "blablabla", line 137, in <module>
plot.annotate(bar.get_height(),
AttributeError: 'BarContainer' object has no attribute 'annotate'
所以似乎我的 BarContainer 或 bar 沒有屬性注釋……坦率地說,即使在查找之后我也不知道這意味著什么。
有人可以幫忙嗎?
感謝和抱歉,如果代碼缺少資訊,請嘗試使其完整。
uj5u.com熱心網友回復:
我可以通過使用axes.pathces而不是plot.patches.
x = [' A6' ,' Q2', ' Q5', ' A5', ' A1', ' A4', ' Q3', ' A3']
y = [ 748, 822, 877, 882 ,1347 ,1381 ,1417, 1929]
fig, ax = plt.subplots(figsize = (10, 7))
ax.bar(x, y)
for bar in ax.patches:
ax.annotate(text = bar.get_height(),
xy = (bar.get_x() bar.get_width() / 2, bar.get_height()),
ha='center',
va='center',
size=15,
xytext=(0, 8),
textcoords='offset points')
plt.xlabel("Car Model")
plt.ylabel("Car Frequency")
plt.title("Frequency of Most Popular Audi Cars")
plt.ylim(bottom=0)
plt.show()
![如何注釋由 2 個不同陣列組成的條形圖?[復制]](https://img.uj5u.com/2021/10/18/2c142f4864314c359560bf5e557a5bd4.png)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/322023.html
標籤:Python 麻木的 matplotlib 注释 条形图
上一篇:像素位置值轉換輸出不正確
