我有一个长格式的数据表,我想绘制不同模拟的结果。同时,可视化应通过另一个变量分为多个方面。
这是一个例子:
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')
创建的图如下所示:
现在,我希望所有线条都具有某种颜色,而一条特定线条应具有另一种特定颜色。
也许有一种方法可以创建仅包含一种颜色的调色板?然后用另一种颜色在上面映射另一个 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()
输出:
关于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/