简体   繁体   中英

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?

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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM