seaborn barplot:随x和hu改变颜色

2024-05-20 21:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据集包含决策支持模型的短期和长期影响的信息。我想用条形图来绘制,有4个条形图:

  • 模型,短期
  • 长期模型
  • 模型关闭,短期
  • 长期模型

下面是一些示例代码:

df = pd.DataFrame(columns=["model", "time", "value"])
df["model"] = ["on"]*2 + ["off"]*2
df["time"] = ["short", "long"] * 2
df["value"] = [1, 10, 2, 4]

sns.barplot(data=df, x="model", hue="time", y="value")
plt.show()

看起来像这样:

barplot

还有许多其他相关的数字,他们建立了颜色惯例。模型开/关以颜色的色调编码。长期与短期是以颜色的饱和度来编码的。假设我给了变量颜色值。如何为条形图中的每个条形图指定单独的颜色?在

{为^ a2}海伯恩·巴普利特只显示color,它为所有元素指定一种颜色,palette只给不同的色调值不同的颜色。在


Tags: 数据代码模型信息示例编码dfmodel
2条回答

现有的答案显示了如何用pyplot来安排barplots。在

不幸的是,我的代码严重依赖于其他seaborn功能,比如错误条等,所以我更希望能够保留seaborn barplot功能,并且只指定我自己的颜色。在

可以将seaborn barplot中的条形图迭代为matplotlib补丁。允许设置颜色、图案填充等:Is it possible to add hatches to each individual bar in seaborn.barplot?

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

df = pd.DataFrame(columns=["model", "time", "value"])
df["model"] = ["on"]*2 + ["off"]*2
df["time"] = ["short", "long"] * 2
df["value"] = [1, 10, 2, 4]

fig, ax = plt.subplots()
bar = sns.barplot(data=df, x="model", hue="time", y="value", edgecolor="white")


colors = ["red", "green", "blue", "black"]
# Loop over the bars
for i,thisbar in enumerate(bar.patches):
    # Set a different hatch for each bar
    thisbar.set_color(colors[i])
    thisbar.set_edgecolor("white")

但是,如果执行此操作,则不会更新图例。可以使用以下代码创建自定义图例。这很复杂,因为我需要为每个图例条目添加多个色块。这显然很复杂:Python Matplotlib Multi-color Legend Entry

^{pr2}$

custom barplot

Seaborn使您可以方便地绘制简单的绘图,但如果您试图偏离它提供的选项,则通常使用直接的matplotlib函数会更简单:

plt.bar(x='model',height='value',data=df.loc[df.time=='short'], width=-0.4, align='edge', color=['C0','C1'])
plt.bar(x='model',height='value',data=df.loc[df.time=='long'], width=0.4, align='edge', color=['C2','C3'])

enter image description here

相关问题 更多 >