1

I am struggling with the following problem. Consider this (simple) example

library(grid)
library(gridExtra)
library(gtable)
library(dplyr)
library(lubridate)
options("digits.secs"=3)

time1 = c('2013-01-03 22:04:21.549', '2013-01-03 22:04:22.549', '2013-01-03 22:04:23.559', '2013-01-03 22:04:24.559' )
value1 = c(1,2,3,4)
data1 <- data_frame(time1, value1)
data1 <- data1 %>%  mutate(time1 = ymd_hms(time1))

time2 = c('2013-01-03 22:04:21.800', '2013-01-03 22:04:22.549', '2013-01-03 22:04:25.559', '2013-01-03 22:04:26.559' )
value2 = c(1,2,3,4)
data2 <- data_frame(time2, value2)
data2 <- data2  %>%  mutate(time2 = ymd_hms(time2))

g1 <- ggplot(data1, aes(x = time1, y = value1)) +geom_point()
g2 <- ggplot(data2, aes(x = time2, y = value2)) +geom_point()


graph_1 <- arrangeGrob(g1, g2, ncol=1)
grid.draw(graph_1)

which gives

enter image description here

as you can see the x- axis is not properly aligned. Any ideas how to do that? Alternative solutions like How to align two plots with ggplot? do not work here.

Many thanks!!

Community
  • 1
  • 1
ℕʘʘḆḽḘ
  • 18,566
  • 34
  • 128
  • 235

2 Answers2

4

You can either use the same limit for both plots (first) or use the facet_grid to align the range for plots (second).

# first method
mx <- ymd_hms("2013-01-03 22:04:21.000")
mn <- ymd_hms("2013-01-03 22:04:27.000")
grid.arrange(g1 + scale_x_datetime(limits=c(mx, mn)),
             g2 + scale_x_datetime(limits=c(mx, mn)))

enter image description here

# second method
names(data1) <- c("time", "value")
names(data2) <- c("time", "value")
df <- bind_rows(first=data1, second=data2, .id="group")
ggplot(df, aes(x=time, y=value)) + geom_point() + facet_grid(group ~ .)

enter image description here

JasonWang
  • 2,414
  • 11
  • 12
  • hi @JasonWang your nice (first) solution breaks if the units of the `y axis` contain a different number of digits. say `value2 = c(100,200,300,400)`. Do you know how to fix that? – ℕʘʘḆḽḘ Jan 17 '17 at 21:31
  • 1
    I think the better way is to use the second one with `facet_grid(group ~ ., scales="free_y")`. For the first one, the way I come up with is to adjust the length of the y label by `scale_y_continuous(labels=function(x) {paste0("00", x)})`. – JasonWang Jan 17 '17 at 22:01
  • 1
    Or you need to figure out what the space is and use the `theme` to adjust the margin. – JasonWang Jan 17 '17 at 22:01
1

You can set the limits of both plots to the range of the data:

xmin <- ymd_hms(min(time1,time2))
xmax <- ymd_hms(max(time1,time2))

g1 <- ggplot(data1, aes(x = time1, y = value1)) + geom_point() +
  theme(axis.title.x = element_blank()) + xlim(xmin, xmax)

g2 <- ggplot(data2, aes(x = time2, y = value2)) + geom_point() +
  xlim(xmin, xmax)

enter image description here

twalbaum
  • 410
  • 1
  • 4
  • 12