R:带有ggplot2的条件标签

R:带有ggplot2的条件标签,r,ggplot2,conditional,R,Ggplot2,Conditional,使用以下问题的答案,我如何有条件地绘制百分比标签,比如我只希望百分比小于50%时,它们才会显示在绘图上?或者更好,如果我只想看到与一个类别相关的百分比?我从一个与您链接的解决方案稍有不同的解决方案开始,因为我发现该示例中的语法有点模糊(尽管它较短)。然后,我为标签及其y位置创建列,并使用geom_text()打印标签 require(ggplot2) 需要(plyr) #设置数据帧,如前一示例所示 cls.grp require(ggplot2) require(plyr) #set up t

使用以下问题的答案,我如何有条件地绘制百分比标签,比如我只希望百分比小于50%时,它们才会显示在绘图上?或者更好,如果我只想看到与一个类别相关的百分比?

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

require(ggplot2)
需要(plyr)
#设置数据帧,如前一示例所示
cls.grp
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))