andrekos
andrekos

Reputation: 2882

R: conditional labels with ggplot2

Using the answer to this question, how can I plot percentage labels conditionally, say I only want them to appear on the plot if percentages are less than 50%? Or better, if I want to see the percentages associated with one category only?

Upvotes: 2

Views: 1951

Answers (1)

Drew Steen
Drew Steen

Reputation: 16607

I started with a slightly different solution than you linked to, because I found the syntax in that example a little murky (although it is shorter). Then I create columns for the labels and their y positions, and plot the labels using 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))

Upvotes: 1

Related Questions