无法在ggplot2 geom_text

问题描述

我正在尝试使用ggplot2将values添加为geom文本:

df <- structure(list(type = structure(1:4,.Label = c("a","b","c","d"),class = "factor"),values = c(0.166667,0.416667,0.083333,0.333333)),class = "data.frame",row.names = c(NA,-4L))

输入:

round(df$values,digits = 4)

出局:

[1] 0.1667 0.4167 0.0833 0.3333

输入:

scales::percent(round(df$values,digits = 4))

出局:

[1] "16.7%" "41.7%" "8.3%"  "33.3%"

您会注意到,结果仅舍入到小数点后一位数值,但我需要两位小数。

以下代码行用于为绘图添加文本:

geom_text(aes(label = scales::percent(round(df$values,digits = 4))),position = position_stack(vjust = 0.5))

如何修改上面的参数以正确取整?谢谢。

解决方法

您可以将accuracyscales::percent()函数一起使用:

geom_text(aes(label = scales::percent(round(df$values,digits = 4),accuracy = 0.01)),position = position_stack(vjust = 0.5))
,

从文档看,正确的代码似乎是:

scales::percent(df$values,accuracy = 0.01)