在不同的seaborn或matplotlib图上分配命名的Colormap /调色板

时间:2016-05-31 03:44:02

标签: python matplotlib ipython seaborn

我有以下虚拟数据。

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")

enter image description here

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

enter image description here

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

提前谢谢!

1 个答案:

答案 0 :(得分:1)

您可以传递字典:

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