【问题标题】:Setting histogram breaks in ggplot2 [duplicate]在ggplot2中设置直方图中断[重复]
【发布时间】:2015-05-05 06:17:06
【问题描述】:

我是 ggplot2 的新手,我正在尝试获得与 hist(results, breaks = 30) 相同的直方图。

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

【问题讨论】:

  • 到目前为止你写了什么代码?

标签: r ggplot2 histogram


【解决方案1】:

如果您使用代码,您将看到 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 值更改为适合您的值。

【讨论】:

  • 好问题,好答案。我经常对此感到疑惑。
【解决方案2】:

添加到 @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

【讨论】:

    猜你喜欢
    • 2015-05-30
    • 1970-01-01
    • 2013-06-20
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 2018-01-02
    相关资源
    最近更新 更多