Search code examples
pythonpandasmethod-chaining

How to plot Pandas .groupby() objects in Seaborn - using method chaining


I would be really grateful for any advice on how to pipe a Pandas .groupby() object into Seaborn

Im trying to plot the .groupby() object but it give me an error message: ValueError: If using all scalar values, you must pass an index

gapminder.\
    groupby('year').\
    agg({'pop' : ['sum'],
         'lifeExp' : ['mean']}).\
    reset_index().\
    pipe((sns.relplot, "data"), x = "pop", y = "lifeExp", kind = "scatter").\
    set(xscale = "log")
plt.show()

Solution

  • Pass a lambda, then you can call the function as you please:

    .pipe(lambda d: sns.relplot(data=d, x="pop", y="lifeExp", kind="scatter"))
    

    Where d represents your DataFrame, passed in whole as the sole argument to .pipe.