Richi W
Richi W

Reputation: 3656

Getting a stacked area plot in R for multivariate time series (an xts object)

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?

Upvotes: 0

Views: 1000

Answers (1)

DatamineR
DatamineR

Reputation: 9618

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

Upvotes: 1

Related Questions