【问题标题】:How to prevent scales::percent from adding decimal如何防止 scales::percent 添加小数
【发布时间】:2019-04-03 23:10:46
【问题描述】:

几天前开始发生这种情况,scales::percent 会在其标签中添加一个小数位,我似乎无法禁用此小数位以在 y 轴上显示整数值。

library(dplyr)
library(ggplot2)

mtcars %>% 
  count(cyl) %>% 
  mutate(prop = n / sum(n)) %>% 
  ggplot(aes(x = cyl, y = prop)) + 
  geom_point() + 
  scale_y_continuous(labels = scales::percent)

【问题讨论】:

    标签: r ggplot2 axis-labels


    【解决方案1】:

    也许不是您问题的直接答案,但我在类似的设置中使用了scales::percent_format 及其accuracy 参数(“要舍入的数字”)。

    mtcars %>% 
        count(cyl) %>% 
        mutate(prop = n / sum(n)) %>% 
        ggplot(aes(x = cyl, y = prop)) + 
        geom_point() + 
        scale_y_continuous(labels = scales::percent_format(accuracy = 5L))
    


    我认为percent 的行为在scales 1.0.0 中发生了变化。请参阅 NEWS 和代码中的更新 here

    【讨论】:

      【解决方案2】:

      只是一个更新,scales::label_percent(accuracy = 1L) 将四舍五入到整数,scales::label_percent(accuracy = 0.1L) 将四舍五入到小数点后一位,依此类推。

      【讨论】:

        猜你喜欢
        • 2012-11-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多