python assign different colors to bars in barplot

时间秒杀一切 提交于 2021-01-29 10:51:18

问题


How to assign different colors to the indices of a barh plot in pandas.DataFrame.plot ? I have a dataframe:

group      clicks_per_visit     bookings_per_visit     rev_per_visit
test1          0.90                0.039                   0.737
test2          0.87                0.034                   0.726

I plot this using:

temp3.plot(kind='barh',subplots=True,grid=True,figsize=(10,7))

to get this plot:

I want the bars to have different colors to highlight the different test groups and I am also open to any other ideas or solutions to make a more 'fancy' visualization of this data.


回答1:


The behavior of pandas' DataFrame.plot() can be complicated and not always intuitive. In theory, you can pass an array of colors to plot(), which will be passed to the underlying plotting function.

In fact, since you are plotting 3 subplots, you would pass a list of 3 sub-lists, each containing the colors of each of your bars.

df.plot(kind='barh', subplots=True,grid=True,figsize=(10,7), color=[['C0','C1']]*3, legend=False)

However, doing this causes the labels on the y-axis to disappear. For some reason, you have to specify the names of the columns you want to use in the call to plot() to get the to appear again.

df.plot(kind='barh',x='group', y=['clicks_per_visit','bookings_per_visit','rev_per_visit'], subplots=True,grid=True,figsize=(10,7), color=[['C0','C1']]*3, legend=False)

Since you are asking for other visualization options, I can show you that you can get roughly the same output, with an easier syntax using seaborn. The only "catch" is that you have to "stack" your dataframe to be long-form instead of wide-form

df2 = df.melt(id_vars=['group'],value_vars=['clicks_per_visit', 'bookings_per_visit', 'rev_per_visit'])
plt.figure(figsize=(8,4))
sns.barplot(y='variable',x='value',hue='group', data=df2, orient='h')
plt.tight_layout()




回答2:


You can do this, it is a very manual way but it will work:

axes = temp3.plot(kind='barh',subplots=True,grid=True,figsize=(10,7))

axes[0].get_children()[0].set_color('r')

This will assign the second bar from the first axis as red, then you can choose the other ones by getting the other axis and children.



来源:https://stackoverflow.com/questions/60885703/python-assign-different-colors-to-bars-in-barplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!