Search code examples
pythonpython-3.xmatplotlibseabornhistogram

How to make line plot following histogram bins


I am trying to make a hist plot with number of bins. After that I want to draw a line plot following bins but I am not able to draw line plot. Can I get some help?

plt.hist(df1_small['fz'], bins=[-5, -4.5, -4, -3.5, -3,-2.5,-2,-1.5,-1,-0.5,0, 0.5, 1,1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5])
sns.kdeplot(df1_small['fz'],fill=True, color = 'Red') 
df1_small['fz'].plot(kind = "kde")
plt.xlabel('Distribution of fz of small particles')
plt.xlim(-5, 5)
plt.show()

This is my code. Plot I got is like this:

enter image description here

If you noticed, line plot is kind of straight line only in 0.

How can I draw line following all bins?

Data is here: https://github.com/Laudarisd/csv


Solution

  • If you just want to trace the outline of plt.hist, use the returned counts and bins:

    width = 0.5
    counts, bins, bars = plt.hist(data=df1_small, x='fz', bins=np.arange(-5, 5.5, width))
    plt.plot(bins[:-1] + width/2, counts)
    


    If you're trying to overlay a sns.kdeplot:

    • set density=True on the histogram to plot probability densities instead of raw counts
    • clip the KDE to the histogram range
    • lower the smoothing bandwidth factor bw_adjust
    plt.hist(data=df1_small, x='fz', bins=np.arange(-5, 5.5, 0.5), density=True)
    sns.kdeplot(data=df1_small, x='fz', clip=(-5, 5), bw_adjust=0.1)