改变seaborn facet网格中的线条样式

时间:2017-05-30 12:05:01

标签: python matplotlib seaborn facet

我有这样的数据集

import numpy as np; np.random.seed(3)
import pandas as pd
import seaborn.apionly as sns
import matplotlib.pyplot as plt

def get_data(n=266, s=[5,13]):
    val = np.c_[np.random.poisson(lam=s[0], size=n),
                np.random.poisson(lam=s[1], size=n)].T.flatten()
    comp = [s[0]]*n +  [s[1]]*n
    ov = np.random.choice(list("ABC"), size=2*n)
    return pd.DataFrame({"val":val, "overlap":ov, "comp":comp})

data1 = get_data(s=[9,11])
data2 = get_data(s=[9,11])
data3 = get_data(s=[9,11])

#option1 combine
for i, df in enumerate([data1,data2,data3]):
    df["data"] = ["data{}".format(i+1)] * len(df)

data = data1.append(data2)
data = data.append(data3)

bw = 2
a = sns.FacetGrid(data, col="overlap",  hue="comp", row="data")
a = (a.map(sns.kdeplot, "val",bw=bw ))
plt.show()

enter image description here

我希望橙色线(对应于数据框中的comp = 11)为黑色和虚线,我该怎么做?

我还想控制某些子图的xlim。这可能吗?

更新

我需要添加facet可以有不同数量的色调级别,如下所示:

import numpy as np; np.random.seed(3)
import pandas as pd
import seaborn.apionly as sns
import matplotlib.pyplot as plt

def get_data(n=266, s=[5,13]):
    val = np.c_[np.random.poisson(lam=s[0], size=n),
                np.random.poisson(lam=s[1], size=n)].T.flatten()
    comp = [s[0]]*n +  [s[1]]*n
    ov = np.random.choice(list("ABC"), size=2*n)
    return pd.DataFrame({"val":val, "overlap":ov, "comp":comp})

def get_data2(n=266, s=[5,13,3]):
    val = np.c_[np.random.poisson(lam=s[0], size=n),
                np.random.poisson(lam=s[1], size=n),
                np.random.poisson(lam=s[1], size=n)].T.flatten()
    comp = [s[0]]*n +  [s[1]]*n + [s[2]]*n
    ov = np.random.choice(list("ABC"), size=3*n)
    return pd.DataFrame({"val":val, "overlap":ov, "comp":comp})

data1 = get_data(s=[9,11])
data2 = get_data2(s=[7,9,11])
data3 = get_data(s=[9,11])

#option1 combine
for i, df in enumerate([data1,data2,data3]):
    df["data"] = ["data{}".format(i+1)] * len(df)

data = data1.append(data2)
data = data.append(data3)

bw = 2
a = sns.FacetGrid(data, col="overlap",  hue="comp", row="data")
a = (a.map(sns.kdeplot, "val",bw=bw ))
plt.show()

enter image description here

1 个答案:

答案 0 :(得分:7)

您可以使用hue_kws参数FacetGrid来更改映射图的颜色或线型。

d = {'color': ['C0', 'k'], "ls" : ["-","--"]}
g = sns.FacetGrid(data, col="overlap",  hue="comp", row="data",hue_kws=d )

如果使用更多色调级别,则需要提供更多颜色和线条样式,例如d = {'color': ['C0', 'k', "crimson"], "ls" : ["-","--", "-."]} 3个色调级别。

要更改xlimits,您可以使用xlim参数

g = sns.FacetGrid(..., xlim=(-10,40) )

enter image description here