![](/img/trans.png)
[英]How to change/set multiple bar colors in matplotlib bar chart (python)
[英]How to put colors in a matplotlib bar chart?
我正在嘗試為下面圖表的每個條形上色。 我需要輸入特定的 colors ,我可以手動設置每個條。
我已經嘗試過使用: #Attempt 1
colors = ['cyan', 'lightblue', 'lightgreen', 'tan','blue']
for patch, color in zip (bar_plot ['boxes'], colors):
patch.set_facecolor (color)
嘗試 1-> 導致錯誤的結果:'AxesSubplot' object 不可下標
#嘗試2
colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']
ax1 = dfPoputationResident.plot('Zona','Total_MSP', kind = 'bar', color = colors);
嘗試 2-> 的結果不起作用,所有條形都是顏色“# 1b9e77”,而不是散布,每個條形都采用一種顏色。
我相信這是因為我的 dataframe 是早先合並的結果。
所以在制作圖表之前,我重置了索引。
dfPoputationResident = dfPoputationResident.reset_index() 這是reset_index后的dataframe
然后我做了:
ax1 = dfPoputationResident.plot ('Zone', 'Total_MSP', kind = 'bar');
但即使在重置索引之后,當我這樣做時
dfPoputationResident.columns
MultiIndex (levels = [['Total_MSP', 'Zone'], ['sum', '']],
codes = [[1,0], [1,0]])
考慮到這些特征,我如何制作條形圖並在每個條形上放置特定的 colors? 請幫幫我。 我是 Python 的新手。
謝謝!
也許是因為您的 dataframe 是多索引列。 嘗試:
dfPoputationResident.columns = ['Zona', 'Total_MSP']
您可以做的另一件事是,當您通過groupby
創建dfPoputationResident
時,您可以執行以下操作:
dfPoputationResident = df.groupby('Zona')['Total_MSP'].sum()
代替
dfPoputationResident = df.groupby('Zona')[['Total_MSP']].sum()
我的意思是,這對我有用:
df = pd.DataFrame({'Zona':list('abcde'),
'Total_MSP':[1,2,3,4,5]})
fig, ax = plt.subplots()
colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']
df.plot.bar(x='Zona',y='Total_MSP',color=colors, ax=ax);
ax.legend(ax.patches, df['Zona'], loc=[1.01,0.5])
Output:
使用 Quang Hoang 提出的 suluction 遵循我的代碼:
dfPoputationResident.columns = ['Zona', 'Total_MSP']
dfPoputationResident = dfPoputationResident.groupby('Zona')['Total_MSP'].sum()
df = pd.DataFrame({'Zona':list('abcde'),
'Total_MSP':[dfPoputationResident.iloc[0],dfPoputationResident.iloc[1],dfPoputationResident.iloc[2],dfPoputationResident.iloc[3],dfPoputationResident.iloc[4]]})
colors = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0']
df.plot.bar(x='Zona',y='Total_MSP',color=colors)
#change the name of month on the x
ax = plt.gca()
names= ['Centro', 'Leste', 'Norte', 'Oeste', 'Sul']
ax.set_xticklabels(names)
x = plt.gca().xaxis
# rotate the tick labels for the x axis
for item in x.get_ticklabels():
item.set_rotation(0)
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.