簡體   English   中英

Matplotliib:為 Pandas 數據框中的多列創建多條形圖

[英]Matplotliib: Creating multi bar charts for multiple columns from a Pandas dataframe

我有一個包含四列的 Pandas 數據框; 第一個是中心類型(x 軸),我希望其余的列按年份顯示為每個中心類型的並排列。 我不確定我做錯了什么,因為我只獲得了 2019 年的值,但我也希望顯示 2018 年和 2017 年。

在此處輸入圖片說明

在此處輸入圖片說明

df = c2

colors = ['steelblue','forestgreen','salmon']

ax = df.plot(kind='bar', color=colors, width=0.7, align='center', stacked=False, rot=60, figsize=(12,6), legend=False, zorder=3)


from matplotlib.ticker import FuncFormatter, MaxNLocator
ax.yaxis.set_major_locator(MaxNLocator(integer=True))

plt.grid(zorder=0)
#plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2))
plt.xlabel("Type of centre")
plt.ylabel("Number")
plt.title("")

ax.spines['bottom'].set_color('gainsboro')
ax.spines['top'].set_color('white') 
ax.spines['right'].set_color('white')
ax.spines['left'].set_color('gainsboro')

ax.yaxis.label.set_color('black')
ax.xaxis.label.set_color('black')

ax.title.set_color('black')

ax.patch.set_facecolor('white')

plt.savefig('images/figure1.png', dpi=300, facecolor=ax.get_facecolor(), transparent=True,  bbox_inches='tight', pad_inches=0.1)
plt.show()
data.shape

您的圖片僅包含一列的原因是df = c2 顯然c2只包含您的 DataFrame 中的一列。 刪除此指令。

作為測試,我只執行了:

df.plot.bar(width=0.7, rot=60, figsize=(12,6), legend=False);

得到以下正確的圖片,有 5 組酒吧,每組 3 酒吧:

在此處輸入圖片說明

僅從上述指令開始,然后決定實際執行剩余的哪條指令。

在我看來,省略的參數是不需要的,因為它們傳遞了各自的默認值。

還要注意末尾的分號。 Jupyter Notebook下工作,需要渲染圖片。 否則(沒有終止分號), <matplotlib.axes._subplots.AxesSubplot at ...>打印在圖片上。

也許您還應該刪除legend=False (保持默認True值並打印圖例)。 否則不清楚具體的柱指的是什么。

暫無
暫無

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

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