R 水平堆叠 ggvis 条形图

R Horizontal Stacked ggvis Barplot

使用这个小数据集:

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

我可以使用 ggvis

轻松创建垂直堆叠条形图
library(ggvis)
df %>%
  ggvis(x=~variable, y=~value, fill=~colour) %>%
  group_by(colour) %>%
  layer_bars()

但我不知道如何制作水平堆叠条形图。我想我应该以某种方式使用 layer_rects,但到目前为止我能得到的最好的只是绘制了一组。

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

那是因为 layer_bars() 会自动叠加,而 layer_rects() 不会。您需要使用 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()) 

给出:


注意: 看这段代码,您可能想知道 stack_lwr_stack_upr_ 参数从何而来。查看 source code 以了解它是如何工作的