【发布时间】:2015-05-05 06:17:06
【问题描述】:
我是 ggplot2 的新手,我正在尝试获得与 hist(results, breaks = 30) 相同的直方图。
如何使用 ggplot2 复制相同的直方图?我正在使用geom_histogram 的binwidth 参数,但我很难让两个直方图看起来相同。
【问题讨论】:
-
到目前为止你写了什么代码?
我是 ggplot2 的新手,我正在尝试获得与 hist(results, breaks = 30) 相同的直方图。
如何使用 ggplot2 复制相同的直方图?我正在使用geom_histogram 的binwidth 参数,但我很难让两个直方图看起来相同。
【问题讨论】:
如果您使用代码,您将看到 R 决定如何分解您的数据:
data(mtcars)
histinfo <- hist(mtcars$mpg)
您将通过histinfo 获得有关休息时间的必要信息。
$breaks
[1] 10 15 20 25 30 35
$counts
[1] 6 12 8 2 4
$density
[1] 0.0375 0.0750 0.0500 0.0125 0.0250
$mids
[1] 12.5 17.5 22.5 27.5 32.5
$xname
[1] "mtcars$mpg"
$equidist
[1] TRUE
attr(,"class")
[1] "histogram"
>
现在您可以调整下面的代码以使您的 ggplot 直方图看起来更像基础直方图。您将不得不更改轴标签、比例和颜色。 theme_bw() 将帮助您按顺序进行一些设置。
data(mtcars)
require(ggplot2)
qplot(mtcars$mpg,
geom="histogram",
binwidth = 5) +
theme_bw()
并将binwidth 值更改为适合您的值。
【讨论】:
添加到 @Konrad 的答案,而不是使用 hist,您可以直接使用 nclass.* 函数之一(请参阅 nclass documentation)。 hist使用了三个函数:
nclass.Sturges使用 Sturges 的公式,隐含地基于 bin 大小 数据的范围。
nclass.scott使用 Scott 选择的正态分布,基于 标准误差的估计,除非它是零 返回 1。
nclass.FD使用 Freedman-Diaconis 选择,基于 四分位间距 (IQR) 除非它恢复到零mad(x, constant = 2),当它也是 0 时,返回 1。
hist function 默认使用nclass.Sturges。
【讨论】: