【问题标题】:Adding second density plot undoes binning in first histogram plot添加第二个密度图会撤消第一个直方图中的分箱
【发布时间】:2019-08-27 00:33:02
【问题描述】:

我在将第二个密度图添加到现有密度 + 直方图 ggplot 时遇到一些问题。也就是说,当我从另一个数据源添加第二个密度图时,它会更改第一个图的直方图中的 bin 数量。

这是说明我的问题的玩具数据/情节

# data
df <- data.frame(var1=rnorm(1e4,0,1), var2=rnorm(1e4,5,1))

# create plot function
plotFunct <- function(data, varName, nBins) {
  p <- ggplot(data, aes_string(x=varName)) + 
              geom_histogram(aes(y=..density..), bins = nBins, fill = "white", colour = "black") +
              geom_density(fill = "#FF6666", alpha = .3)
  return(p)
}

# Now we run the function specifying 40 bins
p <- plotFunct(df, "var1", 40) 
p

所以一切正常。

接下来创建第二个数据集以添加到第一个图形中...

outsideData <- data.frame(outside = rnorm(1e5, -2, 25))

...并将其添加到第一个情节。该数据的分布范围更广,因此为了使图表更易于理解,我们将使用 coord_cartesian() 函数将其限制在预先指定的范围内

p2 <- p + geom_density(data = outsideData, aes(x=outside), colour = "green") + coord_cartesian(xlim = c(-5,5))

p2

第二个密度图是绿色的。请注意,添加它的结果是第一个密度图中的直方图有一个 bin,而不是我们最初指定的 40 个 bin。不知何故,第二个密度图的添加影响了第一个密度图的分箱。然而,原图的密度部分似乎没有受到影响。

谁能告诉我如何恢复到原来的直方图?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    不知道为什么会发生这种情况,但这是一种可能的绕过方式。事实证明,当使用binwidth 而不是bins 时,不会发生您描述的行为。因此,一种方法是根据所需的 bin 数量预先计算合适的 bin 宽度:

    library(ggplot2)
    library(ggplot2)
    
    # data
    df <- data.frame(var1 = rnorm(1e4, 0, 1), var2 = rnorm(1e4, 5, 1))
    
    # create plot function
    plotFunct <- function(data, varName, nBins) {
      vn <- as.name(varName)
      cuts <- pretty(data[,varName], nBins)
      binWidth <- abs(cuts[1]-cuts[2])
      cat("using ", nBins, "bins converted into binwidth", binWidth, "\n\n")
      p <- ggplot(data) +
        geom_histogram(
          aes(x = !!vn, y = ..density..),
          binwidth = binWidth,
          fill = "white",
          colour = "black"
        ) +
        geom_density(aes(x=!!vn), fill = "#FF6666", alpha = .3)
      return(p)
    }
    
    # Now we run the function specifying 40 bins
    p <- plotFunct(df, "var1", 40)
    p
    
    outsideData <- data.frame(outside = rnorm(1e5,-2, 25))
    
    p2 <-
      p + geom_density(
        inherit.aes = FALSE,
        data = outsideData,
        aes(x = outside),
        colour = "green"
      ) + coord_cartesian(xlim = c(-5, 5))
    
    p2
    

    应该制作这个情节:

    【讨论】:

    • 谢谢@teofil!喜欢函数中的惰性 eval。需要学习如何做到这一点。
    猜你喜欢
    • 2016-06-23
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    相关资源
    最近更新 更多