2012-10-01 83 views

回答

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