简体   繁体   English

如何在不创建摘要数据框的情况下在ggplot2中标记堆积条形图?

[英]How do I label a stacked bar chart in ggplot2 without creating a summary data frame?

The following code provides a wonderful stacked bar chart 以下代码提供了精美的堆积条形图

cls.grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d"))
ser <- sample(x=c("neg","pos"),size=80,replace=TRUE, prob=c(30,70))
syrclia <- data.frame(cls.grp,ser)
ggplot(syrclia, aes(cls.grp, fill=ser))+ geom_bar()

I was expecting that with geom_text or stat_summary I would be able to label the percentage who were negative in each group and put it on the corresponding bar. 我期待使用geom_text或stat_summary,我可以在每个组中标记为负数的百分比,并将其放在相应的栏上。 I have tried many permutations and cannot get it to work. 我尝试了许多排列,无法让它发挥作用。 I have even tried manually entering the percentages and forcing the labels where I want them but it does not work. 我甚至尝试手动输入百分比并强制标签在我想要的地方,但它不起作用。 It expects 80 labels and I only want to give four that are negative or perhaps 8 (if one includes the labels for the percentage that are positive). 它需要80个标签,我只想给出4个负数或者8个(如果一个包含百分比的标签,则为正数)。

Do I really have to make an aggregated data frame of my syrclia and plot that? 我真的必须制作我的syrclia的聚合数据框并绘制该图吗?

geom_bar uses stat_bin by default. geom_bar默认使用stat_bin So you should use stat_bin to plot the numbers, tell it to use geom_text and use the newly produced ..count.. as label. 因此,您应该使用stat_bin绘制数字,告诉它使用geom_text并使用新生成的..count..作为标签。

    cls.grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d"))
    ser <- sample(x=c("neg","pos"),size=80,replace=TRUE, prob=c(30,70))
    syrclia <- data.frame(cls.grp,ser)
    library(ggplot2)
    total <- ddply(syrclia, .(cls.grp), function(x) nrow(x))[, 2]
    ggplot(syrclia, aes(cls.grp, fill=ser))+ geom_bar() + 
      stat_bin(geom = "text", 
               aes(label = paste(
                   ..count../get("total", envir = .GlobalEnv)*100,"%")))

HTH HTH 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM