I have the following script
import matplotlib.pyplot as plt
import numpy as np
fig5 = plt.figure()
fig5.subplots_adjust(wspace=0.4, hspace=0.6)
ax5_2 = fig5.add_subplot(212)
std_error = "{:.2f}".format(np.std(df['error']))
ave_error = "{:.2f}".format(np.nanmean(df['error']))
ax5_2.set_title("Error Histogram ave:" + ave_error + " std:" + std_error)
ax5_2.hist(df['error'], range=(0, 2), bins=20)
with that I get
I want to plot the density here. I tried
hist,bin_edges=np.histogram(df['error'], range=(0, 2), bins=20,density=True)
bin_widths=np.diff(bin_edges)
densities = hist / (np.sum(hist) * bin_widths)
plt.bar(bin_edges[:-1], densities, width=bin_widths, align='edge')
# Customize your plot as needed
plt.xlabel('X-axis Label')
plt.ylabel('Density')
plt.title('Density Plot')
with that I got
Is this correct? And second, I thought density plots were smooth line-like plots and not bars.
How can I create the density plot corresponding to the histogram above?
(I tried seaborn completely unrelated histograms and density plots...)
EDIT: I tried mcgusty solution
errors = np.random.randn(100)
df = pd.DataFrame({'errors': errors})
sns.histplot(data=df, x="errors", kde=True)
and I got
but then I tried the equivalent in matplotlib
fig5 = plt.figure()
fig5.subplots_adjust(wspace=0.4, hspace=0.6)
ax5_2 = fig5.add_subplot(212)
ax5_2.hist(errors, range=(-3, 3), bins=9)
hist,bin_edges=np.histogram(errors, range=(-3, 3), bins=9,density=True)
bin_widths=np.diff(bin_edges)
densities = hist / (np.sum(hist) * bin_widths)
plt.bar(bin_edges[:-1], densities, width=bin_widths, align='edge')
Quite different!





sns.histplot(data=errors, bins=10, kde=True)produces the same histogram bars asplt.hist(errors, bins=10, ec='k'). If you want density in seaborn, you have to specify that,sns.histplot(data=errors, bins=10, kde=True, stat='density').plt.hist, you'll see that it has a Booleandensityparameter. The docs show the relevant calculation that's used. The duplicate shows how to calculate the curve.