Home > Mobile >  How to affect a list of colors to histogram index bar in matplotlib?
How to affect a list of colors to histogram index bar in matplotlib?

Time:04-14

I have the the folowing dataframe "freqs2" with index (SD to SD17) and associated values (frequencies) :

    freqs
SD  101
SD2 128
...     
SD17 65

I would like to affect a list of precise colors (in order) for each index. I've tried the following code :

colors=['#e5243b','#DDA63A', '#4C9F38','#C5192D','#FF3A21','#26BDE2','#FCC30B','#A21942','#FD6925','#DD1367','#FD9D24','#BF8B2E','#3F7E44','#0A97D9','#56C02B','#00689D','#19486A']
freqs2.plot.bar(freqs2.index, legend=False,rot=45,width=0.85, figsize=(12, 6),fontsize=(14),color=colors )
plt.ylabel('Frequency',fontsize=(17))

As result I obtain all my chart bars in red color (first color of the list).

Based on similar questions, I've tried to integrate "freqs2.index" to stipulate that the list of colors concern index but the problem stay the same.

CodePudding user response:

It looks like a bug in pandas, plotting directly in matplotlib or using seaborn (which I recommend) works:

import seaborn as sns

colors=['#e5243b','#dda63a', '#4C9F38','#C5192D','#FF3A21','#26BDE2','#FCC30B','#A21942','#FD6925','#DD1367','#FD9D24','#BF8B2E','#3F7E44','#0A97D9','#56C02B','#00689D','#19486A']

# # plotting directly with matplotlib works too:
# fig = plt.figure()
# ax = fig.add_axes([0,0,1,1])
# ax.bar(x=df.index, height=df['freqs'], color=colors)

ax = sns.barplot(data=df, x= df.index, y='freqs', palette=colors)
ax.tick_params(axis='x', labelrotation=45)

plt.ylabel('Frequency',fontsize=17)
plt.show()

Edit: an issue already exists on Github

  • Related