sec.axis与geom_bar()

时间:2019-04-09 09:47:33

标签: r ggplot2 rstudio

我有一个函数,可以在绘图中添加第二个垂直轴,以表示具有相同水平轴的第二个变量。

代码如下:

gplot2eix <- function(data, x, y1, y2, geom, colour= "steelblue", alpha= 1, facDM= NULL){

  library(ggplot2)

  x <- deparse(substitute(x))
  y1 <- deparse(substitute(y1))
  y2 <- deparse(substitute(y2))

  maxAxiY1 <- max(data[[y1]], na.rm= T)
  maxAxiY2 <- max(data[[y2]], na.rm= T)
  minAxiY1 <- min(data[[y1]], na.rm= T)
  minAxiY2 <- min(data[[y2]], na.rm= T)

  offSet <- maxAxiY1-maxAxiY2

  #The divisor/scale multiplier for the secondary axis (facDM) can be introduced manually; but if not, the function calculates it automatically

  if(is.null(facDM)){
  facDM = ((maxAxiY1 - minAxiY1)/(maxAxiY2 - minAxiY2))
  }

  print(facDM)

  vecLim <- c(min(maxAxiY1, maxAxiY2*facDM+offSet, minAxiY1, minAxiY2*facDM+offSet, na.rm = T),
              max(maxAxiY1, maxAxiY2*facDM+offSet, minAxiY1, minAxiY2*facDM+offSet, na.rm = T))

#Add the second axis

  if(geom=="point"){
    graf <- ggplot(data= data, aes(x= data[[x]], y= data[[y1]])) +
      geom_point(y=data[[y2]]*facDM + offSet, aes(colour= colour), alpha= alpha) +
      scale_y_continuous(sec.axis = sec_axis( ~ (. - offSet)/facDM, name = y2), limits = vecLim)

    return(graf)
  }

  if(geom=="line"){
    graf <- ggplot(data= data, aes(x= data[[x]], y= data[[y1]])) +
      geom_line(y=data[[y2]]*facDM + offSet, aes(colour= colour), alpha= alpha) +
      scale_y_continuous(sec.axis = sec_axis( ~ (. - offSet)/facDM, name = y2), limits = vecLim)

    return(graf)
  }

  if(geom=="pointLine"){
    graf <- ggplot(data= data, aes(x= data[[x]], y= data[[y1]])) +
      geom_line(aes(y=data[[y2]]*facDM + offSet, colour= colour), alpha= alpha) +
      geom_point(aes(y=data[[y2]]*facDM + offSet, colour= colour), alpha= alpha) +
      scale_y_continuous(sec.axis = sec_axis( ~ (. - offSet)/facDM, name = y2), limits = vecLim)

    return(graf)
  }

  else{
    stop("geom not valid")
  }

}

此功能仅定义辅助轴的几何,因此有必要在以后添加主轴的几何。以下是如何使用它的示例:

valorsx <- c(20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30)
valorsY1 <- seq(from=900, to=1000, by=1)
valorsY2 <- seq(from=0, to=100, by=1)
valorsY1 <- sample(valorsY1, size=11, replace=TRUE)
valorsY2 <- sample(valorsY2, size=11, replace=TRUE)

dades <- data.frame(varx = valorsx, vary1 = valorsY1, vary2 = valorsY2)

gplot2eix(data=dades, x=varx, y1= vary1, y2= vary2, geom= "pointLine", colour= "red", alpha = 0.6) +
  geom_line() + geom_point()

使用此代码,我得到以下图表:

enter image description here

但是我发现了一个问题:当我使用geom_bar()作为主轴时,此条形图不会被打印:

enter image description here

我尝试了不同的选择:使用geom_col(),定义最大和最小垂直轴以将最小值强制为0,...但没有任何效果。

因此,如果有人知道如何解决该问题,我将不胜感激。

0 个答案:

没有答案