簡體   English   中英

Matplotlib 在子圖中的條形圖上打印值

[英]Matplotlib print values on bars in subplots

使用上面的代碼,我創建了 5 個五個子圖:

values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}

df = pd.DataFrame(data=values)

fig, axs = plt.subplots(2, 3, figsize=(10,6))

eu = axs[0, 0].bar(df["x_values"], df["eu"]
man = axs[0, 1].bar(df["x_values"], df["man"])
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
che = axs[1, 1].bar(df["x_values"], df["che"])
fig.delaxes(axs[1, 2])

他們按應有的方式打印,但我還想將每個條形圖的 y 值添加到條形圖。 就像圖片中一樣在這里輸入圖片描述

我已經嘗試了下面的代碼,但它沒有打印任何東西,沒有錯誤但也沒有打印

for index, value in enumerate(df["corresponding_df"]):
    plt.text(value, index, str(value))

如果我嘗試variable-name.text(value, index, str(value))我得到錯誤'BarContainer' object has no attribute 'text' 如果fig.text再次不打印。 如果axs[subplot-index].text我只能在地塊外的 window 末尾看到一個數字。 有什么建議嗎?

在 matplotlib 3.4.0+ 中使用 bar_label 試試這個:

values = {"x_values" : ["ENN", "CNN", "ENN-CNN"],
"eu" : [11, 79.97, 91],
"man" : [11, 80, 90],
"min3" : [11, 79.70, 90],
"min4" : [11, 79.50, 90],
"che" : [12, 78, 89]}

df = pd.DataFrame(data=values)

fig, axs = plt.subplots(2, 3, figsize=(10,6))

eu = axs[0, 0].bar(df["x_values"], df["eu"])
axs[0,0].bar_label(eu)
man = axs[0, 1].bar(df["x_values"], df["man"])
axs[0,1].bar_label(man)
min3 = axs[0, 2].bar(df["x_values"], df["min3"])
axs[0,2].bar_label(min3)
min4 = axs[1, 0].bar(df["x_values"], df["min4"])
axs[1,0].bar_label(min4)
che = axs[1, 1].bar(df["x_values"], df["che"])
axs[1,1].bar_label(che)
fig.delaxes(axs[1, 2])

Output:

在此處輸入圖像描述

對於文本,可以這樣做:

for ax in axs.flatten():
    for bar in ax.patches:
        ax.text(bar.get_x() + bar.get_width() / 2, 
                bar.get_height()-7,
                bar.get_height(), 
                ha='center',
                color='w')

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM