如何在python中绘制悬挂的根图? [英] How to plot a hanging rootogram in python?
问题描述
受此问题的启发您在python中进行相同类型的绘图?此图旨在以直观的方式很好地展示您的分布与预期分布之间的偏离.它将直方图的条形图悬挂到预期的分布线,因此,在条形图的底部和x轴之间而不是在条形的顶部和预期的分布曲线之间读取与期望值的差异.>
我找不到任何内置函数.
想法是将直方图的每个条移动到条的顶部处于期望值的位置:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
fig, ax = plt.subplots(1, 2)
mu = 10
sig = 0.3
my_data = np.random.normal(mu, sig, 200)
x = np.linspace(9, 11, 100)
# I plot the data twice, one for the histogram only for comparison,
# and one for the rootogram.
# The trick will be to modify the histogram to make it hang to
# the expected distribution curve:
for a in ax:
a.hist(my_data, normed=True)
a.plot(x, mlab.normpdf(x, mu, sig))
a.set_ylim(-0.2)
a.set_xlim(9, 11)
a.hlines(0, 9, 11, linestyle="--")
for rectangle in ax[1].patches:
# expected value in the middle of the bar
exp = mlab.normpdf(rectangle.get_x() + rectangle.get_width()/2., mu, sig)
# difference to the expected value
diff = exp - rectangle.get_height()
rectangle.set_y(diff)
ax[1].plot(rectangle.get_x() + rectangle.get_width()/2., exp, "ro")
ax[0].set_title("histogram")
ax[1].set_title("hanging rootogram")
plt.tight_layout()
哪个给:
HTH
Inspired by this question, how do you make the same kind of plot in python? This plot aims at having a nice visual representation of how your distribution is off of the expected distribution. It hangs the bars of your histogram to the expected distribution line, so the difference to the expected value is read between the bottom of the bar and the x-axis, instead of between the top of the bar and the expected distribution curve.
I could not find any built in function.
The idea is to just move each bar of the histogram plot where the top of the bar is at the expected value:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
fig, ax = plt.subplots(1, 2)
mu = 10
sig = 0.3
my_data = np.random.normal(mu, sig, 200)
x = np.linspace(9, 11, 100)
# I plot the data twice, one for the histogram only for comparison,
# and one for the rootogram.
# The trick will be to modify the histogram to make it hang to
# the expected distribution curve:
for a in ax:
a.hist(my_data, normed=True)
a.plot(x, mlab.normpdf(x, mu, sig))
a.set_ylim(-0.2)
a.set_xlim(9, 11)
a.hlines(0, 9, 11, linestyle="--")
for rectangle in ax[1].patches:
# expected value in the middle of the bar
exp = mlab.normpdf(rectangle.get_x() + rectangle.get_width()/2., mu, sig)
# difference to the expected value
diff = exp - rectangle.get_height()
rectangle.set_y(diff)
ax[1].plot(rectangle.get_x() + rectangle.get_width()/2., exp, "ro")
ax[0].set_title("histogram")
ax[1].set_title("hanging rootogram")
plt.tight_layout()
Which gives:
HTH
这篇关于如何在python中绘制悬挂的根图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!