Search code examples
pythonmatplotlibseabornhistogramlegend

Legend not showing with barless histogram plot in python


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!


Solution

  • 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