![](/img/trans.png)
[英]How can I create a histogram of the values and their count without using the hist() function?
[英]How can I make a histogram using Python just like using R hist function
我正在尝试用Python做直方图,就像我在R中做的那样。我怎么能这样做?
R:
age <- c(43, 23, 56, 34, 38, 37, 41)
hist(age)
蟒蛇:
age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age)
这里的区别是由R和matplotlib默认选择bin的数量的方式引起的。
对于此特定示例,您可以使用:
age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age, bins=4)
复制R风格的直方图 。
如果我们想让matplotlib的直方图看起来像R一般,我们需要做的就是复制R使用的分箱逻辑。 在内部,R使用Sturges的公式 *来计算箱的数量。 matplotlib支持这个开箱即用 ,我们只需要为bins参数传递'sturges'。
age = (43, 23, 56, 34, 38, 37, 41)
plt.hist(age, bins='sturges')
*内部有点复杂,但这让我们大部分都在那里。
简而言之,在plt.hist
调用中使用bins="sturges"
。
bins
:
[...]
'sturges'
的默认方法,只考虑数据大小。 仅适用于高斯数据,低估了大型非高斯数据集的数量。
所以你会得到一个类似于R
'的直方图
import matplotlib.pyplot as plt
import numpy as np
age = np.array((43, 23, 56, 34, 38, 37, 41))
plt.hist(age, bins="sturges", facecolor="none", edgecolor="k")
plt.show()
但请注意,边缘仍然是数据的最小值和最大值。 没有办法自动更改它,但您可以通过bins=(20,30,40,50,60)
手动将这些箱子完全放在R
图表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.