Is there a way to modify the dataframe passed to a facetgrid in seaborn?

Viewed 121

I want to plot different layers in a facetgrid as follows:

grid = sns.FacetGrid(data=tips, row='time', col='sex')
grid.map_dataframe(sns.lineplot, x="total_bill", y="tip", hue="smoker")
grid.map_dataframe(sns.scatterplot, x="total_bill", y="tip", hue="smoker")
#.
#.
#.
# n number of plots

In the above example both the lineplot and scatterplot use the same dataframe tips. Now, I want to change the rows in the dataframe for different plots as follows:

tips = tips.head(n) # n is any number

So, for one plot I may have 120 rows of data whereas for another plot I will have 50 rows and so on.

Is there any way to achieve this?

1 Answers

One thing you can do is to wrap the plot functions around a UDF, then pass that function along with corresponding parameters to map_dataframe:

def my_plot_func(data, plot_func, num_rows, *args, **kwargs):
    plot_func(data=data.head(num_rows), *args, **kwargs)

grid = sns.FacetGrid(data=tips, row='time', col='sex')
grid.map_dataframe(my_plot_func, plot_func=sns.lineplot, num_rows=10, 
                   x="total_bill", y="tip", hue="smoker")
grid.map_dataframe(my_plot_func, plot_func=sns.scatterplot, num_rows=5,
                   x="total_bill", y="tip", hue="smoker")

Output:

enter image description here

Related