Align multiple ggplot2 plots with grid

放肆的年华 提交于 2019-11-27 22:55:29

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)

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.

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)

The solution in ggbio for your problem is to fix the x axis coordinates for the original plots in the following way:

library(ggbio)
p1 <- f()
fixed(p1) <- TRUE
p2 <- f()
fixed(p2) <- TRUE
tracks(p1,p2)

Best,

Yatrosin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!