5

I am trying to draw at stacked area plot using the new ggvis package.

In ggplot, I have managed to do it like this:

d<- data.frame( 
  time=as.numeric( rep( 1:100, 100 ) ), 
  class=as.factor( sample( 7, 100000, replace=TRUE ) ) 
)

t <- as.data.frame( table( d$time, d$class ) )

ggplot( t, aes( x=as.numeric( Var1 ), y=Freq, fill=Var2 ) ) +
  geom_area( stat="identity" )

enter image description here

With ggvis, I have managed to plot the same data in the same layout using bars:

ggvis( t, x=~as.numeric( Var1 ), y=~Freq, fill=~Var2 ) 
  %>% group_by( Var2 )
  %>% layer_bars()

enter image description here

But I have no idea how to tell ggvis that I want areas, not bars. layer_areas doesn't exist, and both layer_paths and layer_ribbons give me wrong results.

I have played around with the props for paths and ribbons, but I can't figure out how to tell ggvis to draw the areas stacked on top of each other.

What is the correct way of drawing stacked area plots using ggvis?

Henrik
  • 65,555
  • 14
  • 143
  • 159
jtatria
  • 527
  • 3
  • 12

1 Answers1

4

I think you need to specify both y (the lower bound of the ribbon) and y2 (the upper bound of the ribbon) for this to work. So try something like

library(dplyr)
library(ggvis)
t %>% 
    group_by(Var1) %>%
    mutate(to = cumsum(Freq), from = c(0, to[-n()])) %>%
    ggvis(x=~as.numeric(Var1), fill=~Var2) %>% 
    group_by(Var2) %>% 
    layer_ribbons(y = ~from, y2 = ~to)

enter image description here

konvas
  • 14,126
  • 2
  • 40
  • 46
  • I was actually looking for a way to have the data transformed automatically for the stacking, but I guess that doing the transform by hand works too. Thanks for showing the exact syntax to use. – jtatria Oct 28 '14 at 14:09