tags:

views:

173

answers:

2

Greetings,

I have three TS variables resembling something like the following:

data <- read.csv(...)
dataA = zoo(data$valueA, data$date)
dataB = zoo(data$valueB, data$date)
dataC = zoo(data$valueC, data$date)

days = seq(start(dataA), end(dataA), "day")

dataAts = na.locf(merge(dataA, zoo(,days)))
dataBts = na.locf(merge(dataB, zoo(,days)))
dataCts = na.locf(merge(dataC, zoo(,days)))

I need to draw dataAts, dataBts and dataCts as a stacked area chart in R. I've tried to use plotrix, but I'm not proficient enough to get the matrix in the right form.

Please Note that dataAts, dataBts and dataCts are not already accumulated, so it is not just a matter of drawing the three of them in the correct order (unless you can come up with a way of summing them up on-the-fly).

Can anyone PLEASE help me?

Thanks in advance...

+1  A: 

I'm sorry I'm not very proficient with time series objects, but if you can get your data into a data frame, I can help.

Assuming you have a data frame with the following columns:

Date    Data    Value

Where Date contains the date, Data contains your A through C labels, and Value contains the value. From that point, the ggplot2 code would be

library(ggplot2)
ggplot(df, aes(Date, Value, fill = Data))+
    geom_area()

I think passing color = "black" to geom_area() nicely delimits the areas, but that's up to your aesthetic taste.

JoFrhwld
+3  A: 

How about something like this?

library(zoo)
library(ggplot2)

data <- data.frame(date=Sys.Date()+1:30,
  valueA=runif(30), valueB=runif(30), valueC=runif(30))

dataA = zoo(data$valueA, data$date)
dataB = zoo(data$valueB, data$date)
dataC = zoo(data$valueC, data$date)

days = seq(start(dataA), end(dataA), "day")

dataAts = na.locf(merge(dataA, zoo(,days)))
dataBts = na.locf(merge(dataB, zoo(,days)))
dataCts = na.locf(merge(dataC, zoo(,days)))

dataABCts <- merge(dataAts,dataBts,dataCts)

# EDIT: Change labels here
colnames(dataABCts) <- c("stock1","stock2","stock3")

stacked <- lapply(colnames(dataABCts),function(i) {
  data.frame(date=index(dataABCts),values=dataABCts[,i],ind=i)
})
stacked <- do.call(rbind,stacked)

ggplot(stacked, aes(x=date, y=values)) + geom_area(aes(fill=ind))
Joshua Ulrich
Excellent!!! Well worth the bounty. Just a couple of questions: how can I change the labels that appear in the right? Is there any way to draw a line with a darker color border in the top of each polygon?Once again, thanks!!
Hugo S Ferreira
The labels are simply the columns names of the `dataABCts` object. Similarly, the axis labels and legend header are the column names of the `stacked` object. I'm not sure what you mean by "a darker color border", but maybe you're looking for something like: `ggplot(stacked, aes(x=date, y=values)) + geom_area(aes(fill=ind),color="black")`?
Joshua Ulrich
also, try: `melt(data, measure = paste("value", c("A","B","C"), sep = ""))`
apeescape