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

2

7

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!

Sanders answered 14/4, 2017 at 16:8 Comment(0)
C
8

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

Charmer answered 14/4, 2017 at 16:30 Comment(1)
Makes sense! Like this way even better than the other answer because I don't have to adjust two things. Thanks!Sanders
O
4

How about something like this:

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

Play with the nudge_x and nudge_y parameters to get the labels to the desired position

Opportunity answered 14/4, 2017 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.