Matplotlib add mathematical expressions and probability density curve in the histogram

Drawing goal

We separate histogram may be used to describe the distribution of quantitative data, and if added a probability density curve as a histogram, can be more clearly to observe such a feature.

Here we will draw a curve of normal distribution probability density About weight based on the frequency distribution of the histogram and the normal distribution probability density calibration equation.

Note: not familiar with the normal distribution, review trouble probability density, frequency distribution histograms and other content about the content of probability theory.

Matplotlib programming

# -*- coding:utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams["font.sans-serif"] = ["KaiTi"]
mpl.rcParams["axes.unicode_minus"] = False

mu = 60.0
sigma = 2.0
x = mu + sigma*np.random.randn(500)

bins = 50

fig, ax = plt.subplots(1, 1)

n, bins, patches = ax.hist(x, bins, density=True, histtype="bar", facecolor="#99FF33", edgecolor="#00FF99", alpha=0.75)

y = ((1/(np.power(2*np.pi, 0.5)*sigma))*np.exp(-0.5*np.power((bins-mu)/sigma, 2)))

ax.plot(bins, y, color="#7744FF", ls="--", lw=2)

ax.grid(ls=":", lw=1, color="gray", alpha=0.2)

ax.text(54, 0.2, r"$y=\frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}}$", {"color":"#FF5511", "fontsize":20})

ax.set_xlabel("体重")
ax.set_ylabel("概率密度")
ax.set_title(r"体重的直方图:$\mu=60.0$, $\sigma=2.0$", fontsize=16)

plt.show()

Finished map

Here Insert Picture Description

Published 515 original articles · won praise 1014 · Views 210,000 +

Guess you like

Origin blog.csdn.net/weixin_43896318/article/details/104328977