【问题标题】:R Making Histograms with Equal Widths and # Of BreaksR制作具有相等宽度和中断数的直方图
【发布时间】:2013-02-21 21:32:25
【问题描述】:

我无法让我的 R 图表的图具有相等的宽度和中断数。

目前,我有

hist(result1,xlim=c(2,4),breaks=10)
abline(v=pi,col="red")
hist(result2,xlim=c(2,4),breaks=10)

我正在尝试将 2 个图表重叠在一起,并使用相同的条形轴 # 和相同的条形宽度。

奇怪的是,当我设置breaks = 10 时,顶部图表的条形有时会比底部多,并且它们的宽度不相等。我没有正确理解breaks参数吗?

【问题讨论】:

  • 这是最好的:在你的答案中,你有一个使用基本图形,一个使用 ggplot2,一个使用 ggplot2 以更复杂的方式。

标签: r ggplot2


【解决方案1】:

我认为使用ggplot2 刻面非常适合这种情节。让我们创建一些数据:

carat1 = diamonds
carat1$id = "one"
carat2 = diamonds
carat2$id = "two"
carat2 = within(carat2, { carat = carat * 1000 })
carat_comb = rbind(carat1, carat2)

让我们做一个情节:

ggplot(aes(x = carat), data = carat_comb) + 
    geom_histogram() + facet_wrap(~ id, ncol = 1)

要在 x 轴完全不同时使这个绘图工作,就是告诉 ggplot 轴值可以独立确定:

ggplot(aes(x = carat), data = carat_comb) + geom_histogram() + 
    facet_wrap(~ id, ncol = 1, scales = "free_x")

【讨论】:

    【解决方案2】:

    我猜你正在将两个直方图绘制在彼此之上:

    par(mfrow=c(2,1))
    

    对于固定休息时间,我建议:

    bins <- seq(2, 4, by=0.1)
    
    hist(results1, breaks=bins, xlim=c(2,4))
    hist(results2, breaks=bins, xlim=c(2,4))
    

    【讨论】:

      【解决方案3】:

      我总是发现您描述的问题也很难处理,一般来说,如果您的数据非常不同,您可能无法做您想做的事情。即便如此,使用ggplot2 图形版本可能会更好:

      library('ggplot2')
      qplot(x = carat, data = diamonds, geom = "histogram", binwidth = 0.1)
      

      如果这种方法适合您,您可以执行以下操作来获得两个图,一个在另一个之上:

      library('grid')
      a <- qplot(x = carat, data = diamonds, geom = "histogram", binwidth = 0.1)
      b <- qplot(x = carat, data = diamonds, geom = "histogram", binwidth = 0.1)
      
      vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y)
      grid.newpage()
      pushViewport(viewport(layout = grid.layout(2, 1)))
      print(a, vp = vplayout(1,1))
      print(b, vp = vplayout(2,1))
      

      【讨论】: