2

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?

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.