简体   繁体   中英

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 them 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.

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