gpt4 book ai didi

r - 向堆积条形图添加标签 - ggvis

转载 作者:行者123 更新时间:2023-12-01 09:20:16 24 4
gpt4 key购买 nike

有没有办法在 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")

绘图输出:

enter image description here

首选输出 - 我将如何修改上面的图表以将标签添加到各个堆栈? :

enter image description here

最佳答案

这不是一个理想的解决方案,但我还是会发布它,因为它可能会为您指明前进的方向。

基本上,我创建了一个新列来指定标签的位置,并使用它将文本放置到图表上。

不过,我还没有想出如何将 % 放到标签上。

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)

enter image description here

关于r - 向堆积条形图添加标签 - ggvis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35477048/

24 4 0