如何使用带有2个单独的y轴刻度的R ggplot覆盖直方图?

时间:2019-07-18 18:34:37

标签: r ggplot2 histogram

我正在尝试使用非常不平衡的类在R中创建多直方图。因此,我希望有两个不同比例的单独y轴,在图的每一侧各有一个。

我已经能够实现使用基本R图形的解决方案,但是我想切换到对图使用ggplot2。目前,我正在使用3个重叠的直方图,使用其中两个的共享比例尺。

到目前为止,我使用ggplot2所能做的就是创建密度直方图(它没有有意义的轴标签并将所有3种数据类型按比例缩放到相同比例)或人为复制代表性不足的数据类,以便它以与主要类相同的比例显示,但这似乎是一个非常棘手的解决方案,并且在图的右侧没有提供第二个轴/比例。

我的基本R图形代码如下:

 hist(vals$nomatch, 
       col=rgb(0, 0, 1, 0.3), 
       axes = FALSE, 
       ylab=NA, 
       xlab="Correlation", 
       main = pTitle,
       xlim = c(pMinBound, pMaxBound), 
       breaks = seq(pMinBound, pMaxBound, length.out = 100))
  axis(2)
  axis(1)
  mtext("Nomatch Frequency", 2, line = 2.5)
  par(new = TRUE)
  hist(vals$match.correct, 
       col = rgb(0, 1, 0, 0.3), 
       axes = FALSE, 
       ylab = NA, 
       xlab = NA, 
       main = NA,
       xlim = c(pMinBound, pMaxBound),
       ylim = c(0, max(table(as.integer(getMatchVals(data)[["match.correct"]] * 100)))),
       breaks = seq(pMinBound, pMaxBound, length.out = 100))
  axis(4)
  mtext("Match Frequency", 4, line = -1.2)
  if (length(vals$match.incorrect != 0)) {
    par(new = TRUE)
    hist(vals$match.incorrect, 
         col = rgb(1, 0, 0, 0.3),
         axes = FALSE,
         ylab = NA,
         xlab = NA,
         main = NA,
         xlim = c(pMinBound, pMaxBound),
         ylim = c(0, max(table(as.integer(getMatchVals(data)[["match.correct"]] * 100)))),
         breaks = seq(pMinBound, pMaxBound, length.out = 100))
  }
  legend("topleft", legend = c("Match.correct", "Match.incorrect", "Nomatch"), fill = c(rgb(0, 1, 0, 0.3), rgb(1, 0, 0, 0.3), rgb(0, 0, 1, 0.3)))

我想使用ggplot2创建与所示相似的直方图。这是我当前的直方图: Current histogram

0 个答案:

没有答案
相关问题