2015-03-19 75 views
0

我有两个geom_line时间序列,每个绘图上有一些geom_text & geom_points。合并ggplot2中的两个绘图并保留绘图的个别特征(geom_text,geom_vline)

其中两个地块还有geom_vline。我想知道是否有可能合并两个,但我没有得到解决方案。

这里有两个地块:

require(zoo) 
require(ggplot2) 

set.seed(10) 

# plot 1: 
tmp1 <- xts(cumsum(rnorm(5000,1,10)), Sys.Date()-5000:1) 
data.tmp1 = data.frame(date=as.Date(index(tmp1)), 
         value=drop(coredata(tmp1))) 
data.tmp1.year.end = data.frame(date=as.Date(index(tmp1[endpoints(tmp1, "years", 1)])), 
           value= drop(coredata(tmp1[endpoints(tmp1, "years", 1)]))) 

plot1 = 
    ggplot(data.tmp1, aes(x=date, y=value)) + 
    geom_line(aes(y=value), size=1) + 
    geom_point(data=data.tmp1.year.end, col="red") + 
    geom_text(data=data.tmp1.year.end, label=data.tmp1.year.end$value, vjust=0, hjust=1) 

# plot 2: 
tmp2 <- xts(cumsum(rnorm(5000,1,100)), Sys.Date()-5000:1) 
data.tmp2 = data.frame(date=as.Date(index(tmp2)), 
         value=drop(coredata(tmp2))) 
data.tmp2.year.end = data.frame(date=as.Date(index(tmp2[endpoints(tmp2, "years", 1)])), 
           value= drop(coredata(tmp2[endpoints(tmp2, "years", 1)]))) 
tmp2.date =as.Date(c("2008-01-01")) 

plot2 = 
    ggplot(data.tmp2, aes(x=date, y=value)) + 
    geom_line(aes(y=value), size=1) + 
    geom_point(data=data.tmp2.year.end, col="red") + 
    geom_vline(xintercept=as.numeric(tmp2.date), linetype="dotted") + 
    geom_text(data=data.tmp2.year.end, label=data.tmp2.year.end$value, vjust=0, hjust=1) 

现在的目标是,plot1和plot2共享一个x轴和个人图表的所有功能都保存在相应的曲线。

结果应该是这样的:

enter image description here

+0

也许'grid.arrange'。制作没有x轴标签的上部绘图并对齐x轴。然后调用'grid.arrange'。 – shadow 2015-03-19 13:33:58

回答

1

你可以试试你的日常数据集和你的年终数据集组合成单一的数据帧,然后使用ggplot的刻面显示上一个日期轴。代码可能看起来像:

data.tmp1 <- cbind(data.tmp1, data_name="tmp1") 
data.tmp1.year.end <- cbind(data.tmp1.year.end, data_name="tmp1") 
data.tmp2 <- cbind(data.tmp2, data_name="tmp2") 
data.tmp2.year.end <- cbind(data.tmp2.year.end, data_name="tmp2") 

data.tmp <- rbind(data.tmp1,data.tmp2) 
data.tmp.year.end <- rbind(data.tmp1.year.end, data.tmp2.year.end) 

ggplot(data.tmp, aes(x=date, y=value)) + 
    geom_line(aes(y=value), size=1) + 
    geom_point(data=data.tmp.year.end, col="red") + 
    geom_text(data=data.tmp.year.end, aes(label=data.tmp.year.end$value), vjust=0, hjust=1) + 
    geom_vline(xintercept=as.numeric(tmp2.date), linetype="dotted") + 
    facet_grid(data_name ~ . , scales="free_y") 

这给图表从`gridExtra`将有助于

enter image description here

+0

谢谢你,先生。 – Pat 2015-03-20 18:08:00