pandas 条形图不采用颜色列表
pandas bar plot not taking list of colours
我正在尝试用不同的颜色为条形图着色,但是当我将颜色列表传递给 color
参数时,它仍然为所有条形图着色。
combi_df = pd.DataFrame(columns=['Labels', 'Number'])
label_list = ['one','two','three','four','five','six','seven','eight']
int_list = [302,11,73,10,68,36,42,30]
combi_df['Labels'] = label_list
combi_df['Number'] = int_list
fig = plt.figure()
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
c = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0','#fdaa48','#6890F0','#A890F0']
combi_df[['Number']].plot(kind='bar',color=c ,legend=True, fontsize=10,ax=ax)
ax.legend(ax.patches, combi_df['Labels'], loc='upper center',bbox_to_anchor=(0.75, 1))
ax.set_xlabel("Labels", fontsize=12)
ax.set_ylabel("Number of occurences", fontsize=12)
plt.show()
我尝试了很多方法来让它工作,包括 How to put colors in a matplotlib bar chart?, and How to set Different Color(s) for Bars of Bar Plot in Matplotlib?
如评论所述,DataFrame.plot.bar
sets colors by column and you only have one column, so one possibility is to switch back to the vanilla pyplot.bar
。
如果您仍想使用 pandas 图,请将 Labels
旋转到列中:
combi_df.pivot(columns='Labels', values='Number').plot.bar(color=c, stacked=True, ax=ax)
或者将其水平放置并将图例替换为yticklabels
:
combi_df.pivot(columns='Labels', values='Number').plot.barh(color=c, stacked=True, legend=False, ax=ax)
ax.set_yticklabels(combi_df['Labels'])
我正在尝试用不同的颜色为条形图着色,但是当我将颜色列表传递给 color
参数时,它仍然为所有条形图着色。
combi_df = pd.DataFrame(columns=['Labels', 'Number'])
label_list = ['one','two','three','four','five','six','seven','eight']
int_list = [302,11,73,10,68,36,42,30]
combi_df['Labels'] = label_list
combi_df['Number'] = int_list
fig = plt.figure()
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
c = ['#1b9e77', '#a9f971', '#fdaa48','#6890F0','#A890F0','#fdaa48','#6890F0','#A890F0']
combi_df[['Number']].plot(kind='bar',color=c ,legend=True, fontsize=10,ax=ax)
ax.legend(ax.patches, combi_df['Labels'], loc='upper center',bbox_to_anchor=(0.75, 1))
ax.set_xlabel("Labels", fontsize=12)
ax.set_ylabel("Number of occurences", fontsize=12)
plt.show()
我尝试了很多方法来让它工作,包括 How to put colors in a matplotlib bar chart?,
如评论所述,DataFrame.plot.bar
sets colors by column and you only have one column, so one possibility is to switch back to the vanilla pyplot.bar
。
如果您仍想使用 pandas 图,请将 Labels
旋转到列中:
combi_df.pivot(columns='Labels', values='Number').plot.bar(color=c, stacked=True, ax=ax)
或者将其水平放置并将图例替换为yticklabels
:
combi_df.pivot(columns='Labels', values='Number').plot.barh(color=c, stacked=True, legend=False, ax=ax)
ax.set_yticklabels(combi_df['Labels'])