簡體   English   中英

如何使用一個圖形上顯示的兩個字典中的值來注釋熊貓條形圖?

[英]How to annotate pandas bar graph with values from two dictionaries displayed on one graph?

我的代碼:

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

ME_Requests = {'John Doe': 105, 'Amanda Doe': 64, 'Maria Doe': 48, 'Dimitrii Doe': 44}
non_ME_Requests = {'John Doe': 47, 'Amanda Doe': 27, 'Maria Doe': 26,}

df = pd.DataFrame({'ME_Request':ME_Requests,
          'non_ME_request':non_ME_Requests})
          

axes = df.plot.bar( title='My Barplots',subplots = True, sharex=True, sharey=True)
for ax in axes:
    for p in ax.patches:
        ax.annotate(str(round(p.get_height(),2)), (p.get_x(), p.get_height()))

plt.gcf().autofmt_xdate()
plt.show()

它返回帶有注釋的兩個單獨的條形圖(藍色和橙色)。 但是,我的目標是在同一圖表上同時顯示(藍色和橙色)。 另外,不確定為什么橙色圖形以不同格式顯示數字,例如:0.0 而不是 0。

在此處輸入圖片說明

有人可以幫我嗎? 先感謝您!

您將subplots=True傳遞給繪圖函數,這就是為什么它創建兩個子圖而不是將兩組條形放在相同的軸上。

如果您使用subplots=False ,則該函數僅返回一個軸而不是數組,因此您需要刪除 for 循環

ax = df.plot.bar( title='My Barplots',subplots = False, sharex=True, sharey=True)
for p in ax.patches:
    ax.annotate('{:.0f}'.format(p.get_height()), (p.get_x(), p.get_height()))

暫無
暫無

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

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