J. Doe
J. Doe

Reputation: 3634

Python Seaborn - FacetGrid dynamic mean axhline

Each Facet has its own mean. How can I plot the according mymean values for each different Facet ? mymean is a list of 3 average values.

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

Upvotes: 2

Views: 2345

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40697

You could create a custom mapping function that will get the data from each Facet, calculate the mean, and plot the resulting value

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

Upvotes: 5

Related Questions