我正在努力解决以下问题。考虑这个(简单)示例
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)
给出了
如您所见,x轴未正确对齐。 任何想法如何做到这一点?像How to align two plots with ggplot?这样的替代解决方案在这里不起作用。
非常感谢!!
答案 0 :(得分:3)
您可以对两个图表使用相同的限制(第一个),也可以使用facet_grid
来对齐图表的范围(第二个)。
# 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)))
# 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 ~ .)
答案 1 :(得分:1)