Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Horizontal Stacked ggvis Barplot

Tags:

r

bar-chart

ggvis

Using this small dataset:

df <- structure(list(colour = structure(c(1L, 2L, 1L, 2L), .Label = c("Black", 
"White"), class = "factor"), variable = c("A", "A", "B", "B"), 
    value = c(1, 2, 0.74, 0.85)), row.names = c(NA, -4L), .Names = c("colour", 
"variable", "value"), class = "data.frame")

I can easily create a vertical stacked barplot with ggvis

library(ggvis)
df %>%
  ggvis(x=~variable, y=~value, fill=~colour) %>%
  group_by(colour) %>%
  layer_bars()

enter image description here

But I cannot figure out how to have a horizontal stacked barplot. I think I am somehow supposed to use layer_rects but the best I could get so far was just one group plotted.

df %>%
  ggvis(x =~value, y=~variable, fill =~ colour) %>%
  group_by(colour) %>%
  layer_rects(x2 = 0, height = band())

enter image description here

like image 255
cdeterman Avatar asked Oct 21 '15 17:10

cdeterman


1 Answers

That's because layer_bars() stacks automatically, layer_rects() doesn't. You need to be explicit about the stacks using compute_stack().

df %>%
  ggvis(y = ~variable, fill = ~colour) %>%
  compute_stack(stack_var = ~value, group_var = ~variable) %>% 
  layer_rects(x = ~stack_lwr_, x2 = ~stack_upr_, height = band()) 

Which gives:

enter image description here


Note: Looking at this code, you might wonder where the stack_lwr_ and stack_upr_ arguments come from. Take a look at the source code to see how it works under the hood

like image 93
Steven Beaupré Avatar answered Nov 15 '22 11:11

Steven Beaupré