rparsingggplot2geom-textdirect-labels

How do I add percentage and fractions to ggplot geom_text label?


I have a dataset where I am interested in looking at a score on a test and the percentage of people experiencing an event:

dat <- data.frame(score = 1:7,
              n.event = c(263,5177,3599,21399,16228,10345,1452),
              n.total = c(877,15725,13453,51226,32147,26393,7875),
              percentage = c(30,33,27,42,50,39,18))

I can plot it with the percentages on the graph like this:

ggplot(data=dat, aes(x=score, y=percentage)) +
  geom_line() +
  geom_text(aes(label = paste0(dat$percentage,"%")))

enter image description here

Or I can plot it with the fractions like this:

ggplot(data=dat, aes(x=score, y=percentage)) +
  geom_line() +
  geom_text(aes(label = paste0("frac(",dat$n.event, ",", dat$n.total, 
  ")")),parse = TRUE)

enter image description here

But I want to have both of them side by side. This doesn't work:

ggplot(data=dat, aes(x=score, y=percentage)) +
  geom_line() +
  geom_text(aes(label = paste0(dat$percentage,"%","frac(",dat$n.event, 
  ",", dat$n.total, ")")),parse = TRUE)

I get this error:

Error in parse(text = as.character(lab)) : :1:3: unexpected input 1: 30%frac(263,877) ^

Thank you for your help!


Solution

  • The problem is that parse=True tells geom_text to use R mathematical annotation (described in ?plotmath). In this annotations, % is a special symbol that must be escaped, and as well, spaces are ignored.

    In order to make peace between % and the rest of the formula, we must escape it, using '%', concatenate it to the previous word using *, and add a space after using ~. The result is:

    ggplot(data=dat, aes(x=score, y=percentage)) +
         geom_line() +
         geom_text(aes(label = paste0(dat$percentage,"*\'%\'~","frac(",dat$n.event, 
                                      ",", dat$n.total, ")")),parse = TRUE)
    

    enter image description here