首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >geom_text中如何始终有固定数目的小数

geom_text中如何始终有固定数目的小数
EN

Stack Overflow用户
提问于 2019-12-18 16:46:17
回答 3查看 1.5K关注 0票数 1

我需要固定数量的小数(在本例中是两个),我无法使它工作,我知道使用roundaccuracy函数,但它似乎对我不起作用。

代码:

代码语言:javascript
复制
library(ggplot2)

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar(color = "steelblue", fill = "#00AFBB", na.rm = T) +
  scale_fill_discrete(drop=FALSE) +
  scale_x_discrete(drop=FALSE) +
  geom_text(aes(label=scales::percent(round(..count../sum(..count..),4))),
            stat='count',vjust = -0.5, size = 4)
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-18 16:56:30

这是内置到scales::percent的。有一个accuracy参数,它被描述为“要舍入的数字”。

代码语言:javascript
复制
ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar(color = "steelblue", fill = "#00AFBB", na.rm = T) +
  scale_fill_discrete(drop=FALSE) +
  scale_x_discrete(drop=FALSE) +
  geom_text(aes(label=scales::percent(..count../sum(..count..), accuracy = 0.01)),
            stat='count',vjust = -0.5, size = 4)
票数 5
EN

Stack Overflow用户

发布于 2019-12-18 16:56:57

scales::percent有一个accuracy参数。

代码语言:javascript
复制
library(ggplot2)

ggplot(mtcars, aes(factor(cyl))) + 
  geom_bar(color = "steelblue", fill = "#00AFBB", na.rm = T) +
  scale_fill_discrete(drop=FALSE) +
  scale_x_discrete(drop=FALSE) +
  geom_text(
    aes(label=scales::percent(round(..count../sum(..count..),4), accuracy = 0.01)),
        stat='count',vjust = -0.5, size = 4)
票数 2
EN

Stack Overflow用户

发布于 2019-12-18 16:55:15

我会把事情掌握在我自己的手中,并创造一个功能:

代码语言:javascript
复制
percent2 <- function(x, accuracy = 2){
    paste0(round(100 * x, digits = accuracy), "%")
}

set.seed(123)
percent2(runif(1), accuracy = 0:5)
# "29%"       "28.8%"     "28.76%"    "28.758%"   "28.7578%"  "28.75775%"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59396655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档