3

Plot.ly has a tutorial on this for Python:

# Add original data
x=['Winter', 'Spring', 'Summer', 'Fall']

y0_org=[40, 80, 30, 10]
y1_org=[20, 10, 10, 10]
y2_org=[40, 10, 60, 80]

# Add data to create cumulative stacked values
y0_stck=y0_org
y1_stck=[y0+y1 for y0, y1 in zip(y0_org, y1_org)]
y2_stck=[y0+y1+y2 for y0, y1, y2 in zip(y0_org, y1_org, y2_org)]

R doesn't seem to have any similar tutorial. I tried to play with the filled area plot tutorial for R, but failed to build a stacked plot.

library(plotly)
p <- plot_ly(x = c(1, 2, 3, 4), y = c(0, 2, 3, 5), fill = "tozeroy")
add_trace(p, x = c(1, 2, 3, 4), y = c(3, 5, 1, 7), fill = "tonexty")

How can I replicate the code above in R/ Plot.ly to create a stacked area chart? Thanks a lot!

Viola Hempel
  • 97
  • 2
  • 11

1 Answers1

3

This is how I got it:

library(plotly)

x <- c('Winter', 'Spring', 'Summer', 'Fall')
y0 <- c(40, 80, 30, 10)
y1 <- c(20, 10, 10, 10)
y2 <- c(40, 10, 60, 80)

y1 <- y0 + y1
y2 <- y1 + y2

p <- ggplot() + 
  geom_area(aes(x, y2, fill = 'green')) +
  geom_area(aes(x, y1, fill = 'blue')) +
  geom_area(aes(x, y0, fill = 'red'))

ggplotly(p)
ytk
  • 2,787
  • 4
  • 27
  • 42
  • Thank you very much @teja-k! The code works perfectly. However, my dataset is not as simple - some of the y0 values can be higher than y2 or y1 values are higher than y2. I'm adding the screenshot of the result I'm getting to the original post. – Viola Hempel Dec 23 '15 at 01:14
  • Thanks a lot! I just figured it out myself too :) You have to create stacked variables, start with the biggest one and move to the one with the smallest value: p <- ggplot() + geom_area(aes(x, y2+y1+y0, fill = 'blue'))+ geom_area(aes(x, y1+y0, fill = 'red'))+ geom_area(aes(x, y0, fill = 'green')) ggplotly(p) – Viola Hempel Dec 23 '15 at 04:27