python为barplot中的条分配不同的颜色 [英] python assign different colors to bars in barplot

查看:68
本文介绍了python为barplot中的条分配不同的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为 pandas.DataFrame.plot 中的 barh 图的索引分配不同的颜色?我有一个数据框:

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))

得到这个情节:

我希望这些条具有不同的颜色以突出显示不同的测试组,并且我也愿意接受任何其他想法或解决方案以使这些数据更加生动"地可视化.

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.

推荐答案

熊猫的 DataFrame.plot()的行为可能很复杂,而且并不总是直观的.理论上,您可以将一组颜色传递给 plot(),后者将传递给底层绘图函数.

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.

实际上,由于要绘制3个子图,因此需要传递3个子列表的列表,每个子列表包含每个条形的颜色.

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)

但是,这样做会使y轴上的标签消失.由于某些原因,您必须指定要在调用 plot()时使用的列的名称,以使再次出现.

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)

由于您要求其他可视化选项,我可以向您展示,您可以使用 seaborn 以更简单的语法获得大致相同的输出.唯一的陷阱"是您必须将数据帧堆叠"为长格式而不是宽格式

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()

这篇关于python为barplot中的条分配不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆