Plot.ly和R中的堆积面积图

时间:2015-12-22 22:31:46

标签: r plotly stacked-area-chart

Plot.ly对此有一个tutorial

# 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似乎没有任何类似的教程。我尝试使用R的填充区域绘图教程,但未能构建堆积图。

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

如何在R / Plot.ly中复制上面的代码来创建堆积区域图表?非常感谢!

1 个答案:

答案 0 :(得分:3)

这就是我得到它的方式:

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)