R Horizontal stacked ggvis Barplot

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 glass panel with ggvis

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

enter image description here

But I canโ€™t understand how to have a horizontal stacked barplot. I think I should somehow use layer_rects , but the best thing I could get so far is just one group.

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

enter image description here

+5
source share
1 answer

This is because layer_bars() automatically added, layer_rects() does not work. You must explicitly specify 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()) 

What gives:

enter image description here


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

+6
source

Source: https://habr.com/ru/post/1234209/


All Articles