使用这个问题的答案,我怎样才能有条件地绘制百分比标签,比如说我只希望它们在百分比小于 50% 时出现在图上?或者更好的是,如果我只想查看与一个类别相关的百分比?
问问题
1753 次
1 回答
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))
于 2012-10-02T18:34:37.350 回答