【问题标题】:R: conditional labels with ggplot2R:带有ggplot2的条件标签
【发布时间】:2012-10-01 03:36:58
【问题描述】:

使用this question 的答案,我如何有条件地绘制百分比标签,比如说我只希望它们出现在百分比小于 50% 的情况下?或者更好的是,如果我只想查看与一个类别相关的百分比?

【问题讨论】:

    标签: r ggplot2 conditional


    【解决方案1】:

    我从与您链接的解决方案略有不同的解决方案开始,因为我发现该示例中的语法有点模糊(尽管它更短)。然后我为标签及其 y 位置创建列,并使用geom_text() 绘制标签。

    require(ggplot2)
    require(plyr)
    
    #set up the data frame, as in the previous example
    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)
    
    #create a data frame with the 'metadata' you will plot
    ct <- ddply(syrclia, "cls.grp", count) #count the occurrences of each cls.group type
    ct <- ddply(ct, "cls.grp", transform, frac=freq/sum(freq)*100) #calculate frequencies as percentages
    ct$frac_to_print <- ""
    
    cutoff <- 30 #define the cutoff, below which you will not plot percentages
    ct$frac_to_print[which(ct$frac > cutoff)] <- paste(ct$frac[which(ct$frac>cutoff)], "%") 
    ct <- ddply(ct, "cls.grp", transform, pos = cumsum(freq)) #calculate the position for each label
    
    ggplot(ct, aes(x=cls.grp, y=freq)) + 
      geom_bar(aes(fill=ser)) + 
      geom_text(aes(x=cls.grp, y=pos, label=frac_to_print))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多