Search code examples
pythonseaborn

How to print the value for each bin on the plot when plotting via seaborn histplot


Lets say I am plotting a histogram with following code, is there a way to print the value of each bin (basically the height of each bar) on the plot?

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

# Fixing random state for reproducibility
np.random.seed(19680801)

x, y = np.random.rand(2, 100) * 4
sns.histplot(x=x, y=y, bins=4, binrange=[[0, 4], [0, 4]])

I am basically want to have a plot like this:

enter image description here


Solution

  • I'm not certain this is possible with seaborn (or at least not without calculating the histogram again separately with numpy/matplotlib). So if you're not tied to seaborn, here's an option for you to consider using matplotlib's hist2d instead:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Fixing random state for reproducibility
    np.random.seed(19680801)
    
    x, y = np.random.rand(2, 100) * 4
    hist, xedges, yedges, _ = plt.hist2d(x, y, bins=4, range=[[0, 4], [0, 4]])
    
    for i in range(len(hist)):
        for j in range(len(hist[i])):
            plt.text(xedges[i] + (xedges[i + 1] - xedges[i]) / 2,
                     yedges[j] + (yedges[j + 1] - yedges[j]) / 2,
                     hist[i][j], ha="center", va="center", color="w")
    
    plt.show()
    

    enter image description here