英文:
How do you preserve hue associations across multiple plots in seaborn?
问题
You can preserve the column-color associations in Plot 2 by specifying the palette parameter in the sns.boxplot
function. Here's how to do it:
sns.boxplot(data=df_2,
orient="h",
palette={"C": "green", "E": "purple"})
plt.show()
This code will make 'C' appear green and 'E' appear purple in Plot 2.
英文:
With the following code as an example, how can I preserve the column-colour associations that you see in Plot 1 in the plot below it, Plot 2?
Is there a way to instruct sns
to 'skip' a hue at specific points? I am looking for a simple workaround that I can control finely, and ideally without manually assigning hex codes.
To be clear, in Plot 2 I would like 'C'
to appear green and 'E'
to appear purple.
Any advice is appreciated, thanks.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(42)
df_1 = pd.DataFrame(np.random.rand(5, 5), columns=['A', 'B', 'C', 'D', 'E'])
df_2 = df_1.drop(['B', 'D'], axis=1)
— Plot 1 —
sns.boxplot(data=df_1,
orient="h")
plt.show()
— Plot 2 —
sns.boxplot(data=df_2,
orient="h")
plt.show()
答案1
得分: 2
将字典传递给 boxplot
的 palette
参数:
# 所有唯一的键
keys = df_1.columns.union(df_2.columns).unique()
# 或者对于更多的数据框:
# set().union(*(df.columns for df in [df_1, df_2, df_3, df_4]))
# ['A', 'B', 'C', 'D', 'E']
# 创建键:颜色字典
colors = dict(zip(keys, sns.color_palette('Set1')))
# 绘制图1
sns.boxplot(data=df_1, orient='h', palette=colors)
# 绘制图2
sns.boxplot(data=df_2, orient='h', palette=colors)
注意:你可以用颜色列表替换 sns.color_palette('Set1')
(例如 [ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00']
)。
如果你使用 seaborn 的调色板,请记住一些调色板的颜色数量有限。要循环使用它们,可以这样做:
import itertools
colors = dict(zip(keys, itertools.cycle(sns.color_palette('Set1'))))
输出:
sns.palplot(colors.values())
英文:
Pass a dictionary to boxplot
's palette
:
# all unique keys
keys = df_1.columns.union(df_2.columns).unique()
# or for more dataframes:
# set().union(*(df.columns for df in [df_1, df_2, df_3, df_4]))
# ['A', 'B', 'C', 'D', 'E']
# create key: color dictionary
colors = dict(zip(keys, sns.color_palette('Set1')))
# plot 1
sns.boxplot(data=df_1, orient='h', palette=colors)
# plot 2
sns.boxplot(data=df_2, orient='h', palette=colors)
NB. you can replace sns.color_palette('Set1')
by a list of colors (e.g. ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00']
).
If you use seaborn's palettes, keep in mind that some are limited in the number of colors. To cycle over them use:
import itertools
colors = dict(zip(keys, itertools.cycle(sns.color_palette('Set1'))))
Output:
sns.palplot(colors.values())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论