Talha002
Talha002

Reputation: 25

How to add legend of DataFrame columns to kdeplot facetgrid?

I am using a DataFrame like below:

df = pd.DataFrame({'a': [20, 30, 50, 55], 'b': [100, 50, 20, 15], 'c':[15, 20, 400, 10]})

And I tried this:

(sns
.FacetGrid(data = df,
            height=10,
            xlim=(0, 10),
            legend_out= True
).add_legend()
.map(sns.kdeplot, data = df, shade = True)
)

And it produced this: https://i.sstatic.net/g9AmS.png

As you can see there is no legend. How can I add it?

Upvotes: 0

Views: 588

Answers (2)

Olof
Olof

Reputation: 11

This works for me

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

d = {"aa": [20, 30, 50, 55], "bb": [100, 50, 20, 15], "cc": [15, 20, 400, 10]}
df = pd.DataFrame(data=d)

g = sns.FacetGrid(data=df, height=10, xlim=(0, 10))
g.map_dataframe(sns.kdeplot, data=df, shade=True)

legend_names = dict(d.keys())
plt.legend(legend_names)
plt.show(block=True)

Upvotes: 0

JohanC
JohanC

Reputation: 80329

Instead of first creating a FacetGrid and then adding kdeplot, it is easier to just call sns.displot(kind='kde', ...). The parameter shade=True has been renamed to fill=True in the latest versions. The legend will be put outside by default.

Also note that with seaborn commands, making a long concatenation of functions is rather confusing and often doesn't result in the desired outcome. (Anyhow, add_legend() would only make sense at the end, after the kde plot has been created.)

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'a': [20, 30, 50, 55], 'b': [100, 50, 20, 15], 'c': [15, 20, 400, 10]})

g = sns.displot(data=df,
                height=5,
                aspect=3,
                kind='kde',
                fill=True,
                facet_kws={'xlim': (-100, 500)})
plt.show()

facetgrid with kde plots

Upvotes: 1

Related Questions