在不同的 seaborn 或 matplotlib 绘图中分配命名的颜色图/调色板

Assigning a named Colormap / palette across different seaborn or matplotlib plots

我有以下虚拟数据。

import seaborn as sb
import pandas as pd
import matplotlib.pyplot as pet

# Generate dummy data
a = np.random.random(70)
b = np.random.random(70) * 1.2
c = np.random.random(70) * 0.5 + 0.5
d = np.random.random(70) * 1.2 - 0.2

# Collate into a DataFrame
df = pd.DataFrame({'Control': a, 'Group1': b, 'Group2': c, 'Group3': d}) 
df = pd.melt(df) # Reshapes the data to allow for easy plotting with seaborn
df.columns = ['Group', 'value']

我想创建 2 个地块。

# Plot all data
sb.swarmplot(data = df, x = "Group", y = "value")

# Plot all data except `Group1`
sb.swarmplot(data = df[df["Group"] != "Group1"], x = "Group", y = "value")

如您所见,2 个绘图之间的颜色映射不一致。如何创建可解析为 seaborn 命令的命名颜色图或调色板,以便保留类别颜色映射?

提前致谢!

你可以传递字典:

pal = dict(Control="k", Group1="b", Group2="g", Group3="r")
sns.swarmplot(..., palette=pal)