r - How do I add percentage and fractions to ggplot geom_text label? -
i have dataset interested in looking @ score on test , percentage of people experiencing 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 percentages on graph this:
ggplot(data=dat, aes(x=score, y=percentage)) +   geom_line() +   geom_text(aes(label = paste0(dat$percentage,"%")))     or can plot fractions 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 want have both of them side side. 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 error:
error in parse(text = as.character(lab)) : :1:3: unexpected input 1: 30%frac(263,877) ^
thank help!
the problem parse=true tells geom_text use r mathematical annotation (described in ?plotmath). in annotations, % special symbol must escaped, , well, spaces ignored.
in order make peace between % , rest of formula, must escape it, using '%', concatenate previous word using *, , add space after using ~. 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)        


Comments
Post a Comment