Align multiple ggplot2 plots with grid

后端 未结 3 1601
情歌与酒
情歌与酒 2020-12-01 18:49

Context

I want to plot two ggplot2 on the same page with the same legend. http://code.google.com/p/gridextra/wiki/arrangeGrob discribes, how to do this. This alrea

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 19:11

    If you don't mind a shameless kludge, just add an extra character to the longest label in p1, like this:

    p1 <- ggplot(data1) +
        aes(x=x, y=y, colour=x) +
        geom_line() + 
        scale_y_continuous(breaks = seq(200, 1000, 200),
                           labels = c(seq(200, 800, 200), " 1000"))
    

    I have two underlying questions, which I hope you'll forgive if you have your reasons:

    1) Why not use the same y axis on both? I feel like that's a more straight-forward approach, and easily achieved in your above example by adding scale_y_continuous(limits = c(0, 10000)) to p1.

    2) Is the functionality provided by facet_wrap not adequate here? It's hard to know what your data structure is actually like, but here's a toy example of how I'd do this:

    library(ggplot2)
    
    # Maybe your dataset is like this
    x <- data.frame(x = c(1, 2),
                    y1 = c(0, 1000),
                    y2 = c(0, 10000))
    
    # Molten data makes a lot of things easier in ggplot
    x.melt <- melt(x, id.var = "x", measure.var = c("y1", "y2"))
    
    # Plot it - one page, two facets, identical axes (though you could change them),
    # one legend
    ggplot(x.melt, aes(x = x, y = value, color = x)) +
        geom_line() +
        facet_wrap( ~ variable, nrow = 2)
    

提交回复
热议问题