-2

I have two dataframes dataA and dataB, both of which contain a time and a value column. Time columns are closely related, but non-identical. Now, I generate two plots with ggplot, e.g.:

plotA <- ggplot(dataA) + geom_line(aes(x = time, y = value))
plotB <- ggplot(dataB) + geom_line(aes(x = time, y = value))

How can I use grid.arrange or a similar function to display the two plots vertically and so that x-axis labels and grid lines align?

nccc
  • 1,095
  • 3
  • 11
  • 20
  • 2
    Please make your code reproducible by adding sample data. – Didzis Elferts Mar 05 '13 at 07:55
  • 1
    Does this [**post**](http://stackoverflow.com/questions/13294952/left-align-two-graph-edges-ggplot) help? Seems like a possible duplicate. – Arun Mar 05 '13 at 08:01
  • "Time columns are closely related, but non-identical." I'm seeking to align the values, not the plot areas. – nccc Mar 05 '13 at 08:19
  • It doesn't "plot" areas. It aligns the left end of the graph between the two and that's what I thought you wanted when you said "**x-axis** labels and grid lines **align**". – Arun Mar 05 '13 at 08:39

1 Answers1

2

You could use facets to align the plots.

Firstly, both data sets need to be combined:

dataAB <- rbind(dataA[c("time", "value")], dataB[c("time", "value")])

A new column indicates the original data set:

dataAB$ind <- c(rep("A", nrow(dataA)), rep("B", nrow(dataB)))

Plot:

library(ggplot2)
ggplot(dataAB) + 
  geom_line(aes(x = time, y = value)) +
  facet_wrap( ~ ind, ncol = 1, scales = "free_y")
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168