pythonseaborncolorbarhistplot

show scale legend of 2D histplot


I want to add a color scale legend to a 2D seaborn dist plot that shows the frequency range of the color scale. An example is mocked up here in ms paint:

a 2D seaborn distplot with a color scale legend

I have looked around and seen many methods to make legends for nominal or ordinal data (e.g. map hue to different categories and then show legends in hue) but nothing for continuous color scales, and nothing applied to 2D distplot. How can this be done? It doesn't need to look exactly like my mockup of course, this is just to illustrate the problem. Ideally it would be a continuous gradient.


Solution

  • You can create a colorbar from ax.collections[0]:

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    iris = sns.load_dataset('iris')
    sns.set_style('darkgrid')
    ax = sns.histplot(iris, x='petal_length', y='sepal_length')
    plt.colorbar(ax.collections[0], ax=ax)
    

    sns.histplot with colorbar