0

I have a multivariate time series and would like to get a stacked area plot. How can this be done using ggplot2?

The data could look likes this:

dates = as.Date(c("2015-04-07","2015-04-08","2015-04-09"))
stocks = xts(c(0.4,0.7,0.9),order.by = dates)
dates = as.Date(c("2015-04-07","2015-04-08","2015-04-09","2015-04-10"))
bonds = xts(c(0.6,0.3,0.1,1),order.by = dates)

example.data = merge(stocks,bonds)

I am quite new to ggplot. The data above is in long format. I have seen examples for wide format. How can I use the index of data for the x-axis without chaanging the data structure?

Joshua Ulrich
  • 168,168
  • 29
  • 327
  • 408
Richi W
  • 3,258
  • 4
  • 17
  • 37

1 Answers1

1

Without changing the structure of the data, you could try the following:

qplot(rep(index(example.data),2), c(coredata(example.data$stocks), 
coredata(example.data$bonds)), geom = "blank") + 
geom_area(aes(colour = rep(c("stocks", "bonds"), each = 4), 
fill = rep(c("stocks", "bonds"),each = 4)))

Which gives:

enter image description here

Or using the melt from reshape2:

library(reshape2)
df <- data.frame(time = index(example.data), melt(as.data.frame(example.data)))
ggplot(df, aes(x = time, y = value)) + 
    geom_area(aes(colour = variable, fill = variable))
DatamineR
  • 10,112
  • 3
  • 24
  • 44