![](/img/trans.png)
[英]Is there a way to show different colors using sns.barplot in python?
[英]python assign different colors to bars in barplot
如何为 pandas.DataFrame.plot 中的 barh 图的索引分配不同的颜色? 我有一个数据框:
group clicks_per_visit bookings_per_visit rev_per_visit
test1 0.90 0.039 0.737
test2 0.87 0.034 0.726
我使用以下方法绘制此图:
temp3.plot(kind='barh',subplots=True,grid=True,figsize=(10,7))
得到这个情节:
我希望条形图有不同的颜色来突出不同的测试组,我也愿意接受任何其他想法或解决方案,以对这些数据进行更“花哨”的可视化。
pandas 的DataFrame.plot()
的行为可能很复杂,而且并不总是很直观。 理论上,您可以将一组颜色传递给plot()
,该数组将传递给底层绘图函数。
事实上,由于您要绘制 3 个子图,因此您将传递 3 个子列表的列表,每个子列表都包含每个条的颜色。
df.plot(kind='barh', subplots=True,grid=True,figsize=(10,7), color=[['C0','C1']]*3, legend=False)
但是,这样做会导致 y 轴上的标签消失。 出于某种原因,您必须指定要在调用plot()
使用的列的名称才能再次出现。
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 使用更简单的语法。 唯一的“问题”是您必须将数据帧“堆叠”为长格式而不是宽格式
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()
你可以这样做,这是一种非常手动的方式,但它会起作用:
axes = temp3.plot(kind='barh',subplots=True,grid=True,figsize=(10,7))
axes[0].get_children()[0].set_color('r')
这会将第一个轴的第二个条指定为红色,然后您可以通过获取另一个轴和子项来选择其他条。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.