开发者

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

开发者 https://www.devze.com 2023-04-03 16:10 出处:网络
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\"))

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

Do I really have to make an aggregated dat开发者_StackOverflowa frame of my syrclia and plot that?


geom_bar uses stat_bin by default. So you should use stat_bin to plot the numbers, tell it to use geom_text and use the newly produced ..count.. as label.

    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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号