在ggplot中添加逗号到geom_text标签

时间:2017-04-19 18:06:31

标签: r parsing ggplot2 scale comma

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

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

我可以用这样的百分比和分数绘制它:

library(ggplot2)
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

但是,我似乎无法弄清楚如何在分数中添加逗号。这不像我想的那样有效:

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

enter image description here

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

数字中的逗号混淆了frac

您可以通过更简单的

查看问题
geom_text(aes(label = "frac(1,000, 2,000)"), parse = TRUE)

enter image description here

我们需要使用frac中的字符来获得所需的输出。如果在语句周围使用双引号,则可以在值周围使用单引号。

geom_text(aes(label = "frac('1,000', '2,000')"), parse = TRUE)

enter image description here

因此,您可以将comma语句包含在标签的frac部分的单引号内。

geom_text(aes(label = paste0("frac('", comma(dat$n.event), "','", 
                            comma(dat$n.total), "')")), parse = TRUE)

整个陈述将是

geom_text(aes(label = paste0(dat$percentage, "*\'%\'~", "frac('", comma(dat$n.event), 
                            "','", comma(dat$n.total), "')")), parse = TRUE)
相关问题