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,"%")))
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)
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!
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With