Align multiple ggplot2 plots with grid

后端 未结 3 1519
情歌与酒
情歌与酒 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)
    
    0 讨论(0)
  • 2020-12-01 19:16

    A cleaner way of doing the same thing but in a more generic way is by using the formatter arg:

    p1 <- ggplot(data1) +
        aes(x=x, y=y, colour=x) +
        geom_line() + 
        scale_y_continuous(formatter = function(x) format(x, width = 5))
    

    Do the same for your second plot and make sure to set the width >= the widest number you expect across both plots.

    0 讨论(0)
  • 2020-12-01 19:18

    1. Using cowplot package:

    library(cowplot)
    plot_grid(p1, p2, ncol=1, align="v")
    


    2. Using tracks from ggbio package:

    Note: There seems to be a bug, x ticks do not align. (tested on 17/03/2016, ggbio_1.18.5)

    library(ggbio)
    tracks(data1=p1,data2=p2)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题