0

I have two geom_line time series with some geom_text & geom_points on each plot.

One of the two plots additionally has geom_vline. I wonder if it is possible to merge two but i failed to get a solution.

Here are the two plots:

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)

The goal now is that plot1 and plot2 share one xaxis and all features of the individual graphs are kept in the corresponding plot.

The result should look like this:

enter image description here

cyberlobe
  • 1,783
  • 1
  • 18
  • 30
Pat
  • 1,299
  • 4
  • 17
  • 40
  • Perhaps `grid.arrange` from `gridExtra` will help. Make the upper plot without x-axis labels and align the x-axis. Then call `grid.arrange`. – shadow Mar 19 '15 at 13:33

1 Answers1

1

You might try combining your daily data sets and your year end data sets into single data frames and then using ggplot's faceting to display on a single date axis. Code could look like:

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")

which gives the chart

enter image description here

WaltS
  • 5,410
  • 2
  • 18
  • 24