在 ggplot2 中设置直方图中断

Setting histogram breaks in ggplot2

我是 ggplot2 的新手,我正在尝试获得与 hist(results, breaks = 30).

相同的直方图

如何使用 ggplot2 复制相同的直方图?我正在使用 geom_histogrambinwidth 参数,但我很难使两个直方图看起来完全相同。

如果您使用代码,您将看到 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 uses Sturges' formula, implicitly basing bin sizes on the range of the data.

nclass.scott uses Scott's choice for a normal distribution based on the estimate of the standard error, unless that is zero where it returns 1.

nclass.FD uses the Freedman-Diaconis choice based on the inter-quartile range (IQR) unless that's zero where it reverts to mad(x, constant = 2) and when that is 0 as well, returns 1.

hist function默认使用nclass.Sturges.