R and stacked area charts?
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 the开发者_Python百科m up on-the-fly).
Can anyone PLEASE help me?
Thanks in advance...
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))
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.
精彩评论