簡體   English   中英

如何在 matplotlib 中的一個圖上從 Pandas 數據框中添加多個條形圖?

[英]How do I add multiple bar graphs from a pandas dataframe on one plot in matplotlib?

我有兩個不同的數據框:

df_test1 = pd.DataFrame(
    [['<18', 80841], ['18-24', 334725], ['25-44', 698261], ['45-64', 273087], ['65+', 15035]],
    columns = ['age_group', 'total_arrests']
)

在此處輸入圖片說明

df_test2 = pd.DataFrame(
    [['<18', 33979], ['18-24', 106857], ['25-44', 219324], ['45-64', 80647], ['65+', 4211]],
    columns = ['age_group','total_arrests']
)

在此處輸入圖片說明

我使用 matplotlib 創建了以下圖:

fig, ax = plt.subplots()

ax.bar(df_test1.age_group, df_test1.total_arrests, color = 'seagreen')
ax.bar(df_test2.age_group, df_test2.total_arrests, color = 'lightgreen')
ax.set_xlabel('Age Group')
ax.set_ylabel('Number of Arrests')
ax.set_title('Arrests vs. Felony Arrests by Age Group')
plt.xticks(rotation=0)
plt.legend(['All Arressts', 'Felony Arrests'])

ax.yaxis.set_major_formatter(
ticker.FuncFormatter(lambda y,p: format(int(y), ','))
)

for i,j in zip(df_test1.age_group, df_test1.total_arrests):
    ax.annotate(format(j, ','), xy=(i,j))

for i,j in zip(df_test2.age_group, df_test2.total_arrests):
    ax.annotate(format(j, ','), xy=(i,j))

plt.show()

在此處輸入圖片說明

我期待 2 個單獨的條形圖,每個數據df_test1.total_arrests列一個, df_test1.total_arrestsdf_test2.total_arrests但我得到了一個堆積條形圖。 我怎樣才能得到一個條形相鄰的圖表,類似於這里的圖表Matplotlib 在一個圖表中繪制多個條形 我嘗試將我的代碼調整為該示例中的代碼,但我無法理解。

只有兩個酒吧,這相當容易。 解決方案是將刻度線“邊緣”上的條形對齊,一個條形向左對齊,另一個向右對齊。

重復相同的邏輯以正確對齊注釋。 其中一半左對齊,其他右對齊

fig, ax = plt.subplots()

ax.bar(df_test1.age_group, df_test1.total_arrests, color = 'seagreen', width=0.4, align='edge')
ax.bar(df_test2.age_group, df_test2.total_arrests, color = 'lightgreen', width=-0.4, align='edge')
ax.set_xlabel('Age Group')
ax.set_ylabel('Number of Arrests')
ax.set_title('Arrests vs. Felony Arrests by Age Group')
plt.xticks(rotation=0)
plt.legend(['All Arressts', 'Felony Arrests'])
ax.yaxis.set_major_formatter(
matplotlib.ticker.FuncFormatter(lambda y,p: format(int(y), ','))
)

for i,j in zip(df_test1.age_group, df_test1.total_arrests):
    ax.annotate(format(j, ','), xy=(i,j))

for i,j in zip(df_test2.age_group, df_test2.total_arrests):
    ax.annotate(format(j, ','), xy=(i,j), ha='right')

plt.show()

在此處輸入圖片說明

如果您有 2 個以上的柱,則情況會更復雜(請參閱上面鏈接的代碼)。 您將更輕松地使用seaborn ,但您必須稍微轉換您的數據seaborn

df = pd.merge(left=df_test1, right=df_test2, on='age_group')

df.columns=['age_group','all_arrests', 'felonies']
df = df.melt(id_vars=['age_group'], var_name='Type', value_name='Number')

fig, ax = plt.subplots()
sns.barplot(y='Number',x='age_group',hue='Type', data=df, hue_order=['felonies','all_arrests'])

在此處輸入圖片說明

暫無
暫無

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

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