python - Seaborn 的 relplot : Is there a way to assign a specific color to all lines and another color to another single line when using the hue argument?

标签 python seaborn

我有一个长格式的数据表,我想绘制不同模拟的结果。同时,可视化应通过另一个变量分为多个方面。

这是一个例子:

import seaborn as sns
import pandas as pd
import numpy as np

sim = ['a'] * 100 + ['b'] * 100 + ['c'] * 100
var = (['u'] * 50 + ['v'] * 50)*3

x = np.linspace(0, 50, 50)
x = np.hstack([x]*6)

y = np.random.rand(300)

df = pd.DataFrame({'x':x, 'y':y, 'sim':sim, 'var':var})

sns.relplot(data=df, x='x', y='y', kind='line', col='var', hue='sim')

创建的图如下所示:

Plot

现在,我希望所有线条都具有某种颜色,而一条特定线条应具有另一种特定颜色

也许有一种方法可以创建仅包含一种颜色的调色板?然后用另一种颜色在上面映射另一个 sns.lineplot ?也许使用 matplotlib 手动创建绘图会更容易,但我的实际数据框包含更多变量和模拟,这就是 seaborn 派上用场的原因。

最佳答案

编辑代码库注释

如果你想要颜色df['sim] == 'a'使用此代码:

import seaborn as sns
import pandas as pd
import numpy as np

sim = ['a'] * 100 + ['b'] * 100 + ['c'] * 100
var = (['u'] * 50 + ['v'] * 50)*3

x = np.linspace(0, 50, 50)
x = np.hstack([x]*6)

y = np.random.rand(300)

df = pd.DataFrame({'x':x, 'y':y, 'sim':sim, 'var':var})

g = sns.relplot(data=df, x='x', y='y', kind='line', col='var',
                units='sim', estimator=None, color='0.7')

for i , ax in enumerate(g.axes.flatten()):
    sns.lineplot(data=df[df['sim']=='a'], x='x', y='y', ax=ax, color='red', estimator=None, label='a', lw=2)
    ax.legend(title='sim', bbox_to_anchor=(1, 1), loc='upper left') if i == 1 else ax.legend().remove()

输出:

enter image description here

关于python - Seaborn 的 relplot : Is there a way to assign a specific color to all lines and another color to another single line when using the hue argument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68903545/

相关文章:

python - 根据Python中defaultdict的特定列的值对csv列进行排序

python - 使用函数控制Python线程

python - 如何访问多索引 Panda 数据框中的先前行

python - Seaborn tsplot 在 x 轴上更改标签

python - Matplotlib 直方图或 Seaborn 分布图的箱上没有轮廓

python - 如何使用多个自定义值标记条形

python - 当我的 X 变量是分类变量时,如何偏移 X 轴上的误差线(matplotlib)

javascript - 按 html 按钮时在后台运行终端命令

python - 如何在 matplotlib/seaborn 上使用 LaTex 符号设置轴标签的字体大小?

python - 在 Python 中发送带有 HTML+plain_text 电子邮件的 PDF 附件