在ggplot2中设置直方图中断

时间:2015-05-05 06:17:07

标签: r ggplot2 histogram

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

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

添加 @Konrad 的答案,而不是使用hist,您可以直接使用其中一个nclass.*函数(请参阅nclass documentation)。 hist使用了三个函数:

  

nclass.Sturges使用Sturges&#39;公式,隐含地基于bin大小   数据的范围。

     

nclass.scott使用Scott的选择进行基于的正态分发   标准误差的估计值,除非它为零   返回1.

     

nclass.FD使用Freedman-Diaconis选择   四分位数范围(IQR),除非它归还的位置为零   mad(x, constant = 2),当该值为0时,返回1.

hist function默认使用nclass.Sturges