Align multiple plots in ggplot2 when some have legends and others don't

前端 未结 6 1463
离开以前
离开以前 2020-11-30 03:09

I have used the method indicated here to align graphs sharing the same abscissa.

But I can\'t make it work when some of my graphs have a legend and others don\'t.

6条回答
  •  一个人的身影
    2020-11-30 04:03

    Using grid.arrange

    library(ggplot2)
    library(reshape2)
    library(gridExtra)
    
    x = seq(0, 10, length.out = 200)
    y1 = sin(x)
    y2 = cos(x)
    y3 = sin(x) * cos(x)
    df1 <- data.frame(x, y1, y2)
    df1 <- melt(df1, id.vars = "x")
    g1 <- ggplot(df1, aes(x, value, color = variable)) + geom_line()
    df2 <- data.frame(x, y3)
    g2 <- ggplot(df2, aes(x, y3)) + geom_line()
    
    #extract the legend from the first graph
    temp <- ggplotGrob(g1)
    leg_index <- which(sapply(temp$grobs, function(x) x$name) == "guide-box")
    legend <- temp$grobs[[leg_index]]
    
    #remove the legend of the first graph
    g1 <- g1 + theme(legend.position="none")
    
    #define position of each grobs/plots and width and height ratio
    grid_layout <- rbind(c(1,3),
                        c(2,NA))
    grid_width <- c(5,1)
    grid_heigth <- c(1,1)
    
    
    grid.arrange(
      grobs=list(g1, g2,legend),
      layout_matrix = grid_layout,
      widths = grid_width,
      heights = grid_heigth)
    

提交回复
热议问题