有没有办法将标签附加到ggvis
中的堆积条形图?
示例代码:
plotData = data.frame(v1 = c("ABC", "ABC", "ABC", "XYX","XYX","XYX"),
v2 = c("A" , "B" , "C" , "X" ,"Y" ,"Z" ),
value = c(30 , 60 , 10 , 20 , 40 , 40 ))
plotData %>%
ggvis(y = ~v1, fill = ~v2) %>%
compute_stack(stack_var = ~value, group_var = ~ v1) %>%
layer_rects(x = ~stack_lwr_, x2 = ~stack_upr_, height = band()) %>%
add_axis("y", title = "Variable") %>%
add_axis("x", title = "Percentage")
绘图输出:
首选输出 - 如何修改上面的图表以向各个堆栈添加标签? :
答案 0 :(得分:1)
这不是一个理想的解决方案,但我会发布它,因为它可能会给你一个前进的方向。
基本上,我创建了一个新列来指定标签的位置,并使用它来将文本放到图表上。
我还没想出如何在标签上加上%。
library(ggvis)
plotData = data.frame(v1 = c("ABC", "ABC", "ABC", "XYX","XYX","XYX"),
v2 = c("A" , "B" , "C" , "X" ,"Y" ,"Z" ),
value = c(30 , 60 , 10 , 20 , 40 , 40 ))
library(dplyr)
## This can be shortened, but I'm leaving it as is to show the steps
plotData <- plotData %>%
group_by(v1) %>%
mutate(cs = cumsum(value)) %>%
mutate(pos = ifelse(is.na(cs - lag(cs)), cs, (cs - lag(cs)))) %>%
mutate(pos = cs - (pos/2)) %>%
ungroup
plotData %>%
ggvis(y = ~v1, fill = ~v2) %>%
compute_stack(stack_var = ~value, group_var = ~ v1) %>%
layer_rects(x = ~stack_lwr_, x2 = ~stack_upr_, height = band()) %>%
add_axis("y", title = "Variable") %>%
add_axis("x", title = "Percentage") %>%
layer_text(x = prop("x", ~pos),
y = prop("y", ~v1, scale = "ycenter"),
text:=~value, fill := "white", fontSize:=20)