如何在ggplot geom_text标签中添加百分比和分数?

时间:2017-04-14 16:08:57

标签: r parsing ggplot2 geom-text direct-labels

我有一个数据集,我有兴趣查看测试分数和遇到事件的人数百分比:

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))

我可以使用图表上的百分比来绘制它:

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

enter image description here

或者我可以用这样的分数绘制它:

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

但我希望他们两个并排。这不起作用:

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)

我收到此错误:

解析时出错(text = as.character(lab)):: 1:3:意外输入 1:30%压裂(263,877)       ^

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

问题是parse=True告诉geom_text使用R数学注释(在?plotmath中描述)。在此注释中,%是必须转义的特殊符号,并且空格也会被忽略。

为了在%和公式的其余部分之间实现和平,我们必须使用'%'将其转义,使用*将其连接到上一个单词,并添加空格使用~后。结果是:

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

答案 1 :(得分:2)

这样的事情怎么样:

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)

使用nudge_xnudge_y参数进行游戏以获得所需位置的标签