-1

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

enter image description here

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

enter image description here

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

enter image description here

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)

and I got enter image description here and

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')

enter image description here

Quite different!

3

1 Answer 1

0

I think using seaborn.histplot can help in adding a density-plot over the bars.

Something like this should probably work:

import numpy as np
import pandas as pd
import seaborn as sns

errors = np.random.randn(100)
df = pd.DataFrame({'errors': errors})
sns.histplot(data=df, x="errors", kde=True)
Sign up to request clarification or add additional context in comments.

1 Comment

I tried your solution but the results were quite different (see EDIT)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.