Function to build double y axis graph in ggplot2

后端 未结 3 1002

I am testing a function to build a double y axis graph in ggplot2. It works but I can\'t get some elements from the input graphics. I have built these two graphs with two data f

3条回答
  •  不要未来只要你来
    2021-02-20 01:39

    I used some guys code to build my own here

    grid.newpage()
    
    # two plots
    p1 <- ggplot(fuel, aes(x=date, y=mpg)) + geom_line() + 
      theme_bw() + xlab("Date") + ylab("MPG (Black)")
    p2 <- ggplot(fuel, aes(x=date, y=avg.temp)) + 
      xlab("Date") + ylab("AVG Temp (Red)") +
      geom_line(colour="red") + theme_bw() + 
      theme(axis.title.y=element_text(angle = -90)) %+replace% 
      theme(panel.background = element_rect(fill = NA))
    
    # extract gtable
    g1 <- ggplot_gtable(ggplot_build(p1))
    g2 <- ggplot_gtable(ggplot_build(p2))
    
    # overlap the panel of 2nd plot on that of 1st plot
    pp <- c(subset(g1$layout, name == "panel", se = t:r))
    g <- gtable_add_grob(g1, 
                         g2$grobs[[which(g2$layout$name == "panel")]], 
                         pp$t, pp$l, pp$b, pp$l)
    
    # axis tweaks
    alab <- g2$grobs[[which(g2$layout$name=="ylab")]]
    ia <- which(g2$layout$name == "axis-l")
    ga <- g2$grobs[[ia]]
    ax <- ga$children[[2]]
    ax$widths <- rev(ax$widths)
    ax$grobs <- rev(ax$grobs)
    ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + 
      unit(0.15, "cm")
    g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], 
                         length(g$widths) - 1 )
    g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], 
                         length(g$widths) - 1 )
    g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 2, pp$b)
    g <- gtable_add_grob(g, alab, pp$t, length(g$widths) - 1, pp$b)
    
    grid.draw(g)
    

提交回复
热议问题