在构面图上添加标签数据框中的标签

时间:2017-07-07 23:08:50

标签: r ggplot2

我有这个情节

IAM

我想在每个堆叠的Z上面添加一个标签,它是2个组件的总和,所以我构建了一个标签数据框并使用geom_text:

dat = data.frame(group = c("A","A","B","B"), pct = c(.2,.3,.5,.4), subgroup = c("D","E","D","E"), x = c("Z","Z","Z","Z"))


ggplot(data = dat, aes(x = factor(x), y  =pct, fill= subgroup ))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)

但由于子组不在数据帧中,我收到错误

LABEL = data.frame(x = c("Z","Z"),  y = c(.5,.9), group = c("A","B"))
    ggplot(data = dat, aes(x = factor(x), y  =pct, fill= subgroup ))+geom_bar(position = "stack", stat = "identity")+facet_wrap(~group)+geom_text(aes(x= x,y=y ,label=labs), data = LABEL, vjust=-.2, size = 3)

但我不想在数据框中使用子组,因为我正在绘制的标签是每个子组的总和。

上面的示例每个方面有一个堆叠条,但解决方案应适用于每个小平面图的任意数量的堆叠条。

1 个答案:

答案 0 :(得分:2)

这是你想要的吗?

dat = data.frame(group = c("A","A","B","B"), 
                 pct = c(.2,.3,.5,.4), 
                 subgroup = c("D","E","D","E"), 
                 x = c("Z","Z","Z","Z"))

LABEL = data.frame(x = c("Z","Z"),  
                   y = c(.5,.9), 
                   group = c("A","B"))

ggplot(data = dat, aes(x = factor(x), y  =pct)) +
    geom_bar(aes(fill= subgroup), position = "stack", stat = "identity") +
    facet_wrap(~group) +
    geom_text(aes(x= x,y=y ,label=y), data = LABEL, vjust=-.2, size = 3)