Python Seaborn - FacetGrid动态意味着axhline

时间:2018-02-15 11:47:42

标签: python pandas matplotlib seaborn

每个Facet都有自己的意思。如何为每个不同的Facet绘制相应的mymean值? mymean是3个平均值的列表。

from random import randint
import pandas as pd
names = ["Jack", "Ernest", "Wilde"]
a = pd.DataFrame({"Value": [randint(0, 100) for i in range(len(names)*5)],
                  "Year": [y for i in range(len(names)) for y in range(2014,2019)], 
                  "Name": [name for name in names for i in range(5)]})

mymean = a.groupby(["Name"])["Value"].mean()

sns.set(style="white", context="talk")
grid = sns.FacetGrid(a, col="Name", hue="Name", col_wrap=3, size=3, sharey=False)
grid.map(plt.axhline, y=60, ls=":", c=".5")
grid.map(plt.plot, "Year", "Value", marker="o", ms=5)
grid.fig.tight_layout(w_pad=1)

enter image description here

1 个答案:

答案 0 :(得分:2)

你可以创建一个自定义映射函数,它将从每个Facet获取数据,计算平均值,并绘制结果值

def plot_mean(data,**kwargs):
    m = data.mean()
    plt.axhline(m, **kwargs)

names = ["Jack", "Ernest", "Wilde"]
a = pd.DataFrame({"Value": [np.random.randint(0, 100) for i in range(len(names)*5)],
                  "Year": [y for i in range(len(names)) for y in range(2014,2019)], 
                  "Name": [name for name in names for i in range(5)]})
mymean = a.groupby(["Name"])["Value"].mean()
sns.set(style="white", context="talk")
grid = sns.FacetGrid(a, col="Name", hue="Name", col_wrap=3, size=3, sharey=False)

# To get the data passed to our custom function, 
# we need to add "Value" as a second argument to FacetGrid.map()
grid.map(plot_mean, 'Value', ls=":", c=".5")

grid.map(plt.plot, "Year", "Value", marker="o", ms=5)
grid.fig.tight_layout(w_pad=1)

enter image description here