1

I am trying to plot a kde plot in seaborn using the histplot function, and removing later the bars of the histogram in the following way (see last part of the accepted answer here):

fig, ax = plt.subplots()
sns.histplot(data, kde=True, binwidth=5,  stat="probability", label='data1', kde_kws={'cut': 3})

The reason for using histplot instead of kdeplot is that I need to set a specific binwidth. The problem I have that I cannot print out the legend, meaning that

ax.legend(loc='best')

does nothing, and I receive the following message: No handles with labels found to put in legend.

I have also tried with

handles, labels = ax.get_legend_handles_labels()
plt.legend(handles, labels, loc='best')

but without results. Does anybody have an idea of what is going on here? Thanks in advance!

2
  • provide the sample dataset Commented Nov 13, 2021 at 12:33
  • I don't know if this is the answer since I don't know what output to expect, but I think you can add this. ax = sns.kdeplot(data, x="flipper_length_mm", label='kde density') Commented Nov 13, 2021 at 12:54

1 Answer 1

3

You can add the label for the kde line via the line_kws={'label': ...} parameter.

sns.kdeplot can't be used directly, because currently the only option is the default scaling (density).

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

data = np.random.normal(0.01, 0.1, size=10000).cumsum()
ax = sns.histplot(data, kde=True, binwidth=5, stat="probability", label='data1',
                  kde_kws={'cut': 3}, line_kws={'label': 'kde scaled to probability'})
ax.containers[0].remove() # remove the bars of the histogram
ax.legend()
plt.show()

sns.kdeplot scaled to probability, with legend

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.