【问题标题】:ggplot scales unit format thousands one decimal placeggplot 缩放单位格式千位小数
【发布时间】:2017-06-17 01:54:09
【问题描述】:

完成 R/RStudio/tidyverse 的新手。 使用 R 3.4.0“你愚蠢的黑暗”/RStudio 1.0.136。 试图格式化 y 轴以显示千位到小数点后一位。 我正在使用 : scale_y_continuous(labels = scales::unit_format("k", 1e-3)) 但显示为整数。如何显示 1 个小数位,而不是 30k,我得到 30.1k?

谢谢

【问题讨论】:

  • 你能添加一个 MWE 吗?

标签: r ggplot2 rstudio tidyverse


【解决方案1】:

如果您需要更灵活的东西,我建议您使用自己的自定义函数并将其插入scale_y_continuous,如下所示:

library(ggplot2)

# custom formatting function
scaleFUN <- function(x) sprintf("%.1fk", x/1000)

# setup diamonds dataset to display something in the thousands
diamonds2 <- diamonds
diamonds2$price <- diamonds2$price * 100

# make your plot and label using the custom scaleFUN function
ggplot(diamonds2, aes(x = carat, y = price)) + 
  geom_point() + 
  scale_y_continuous(name = 'Price ($K)', 
                     labels = scaleFUN)

【讨论】:

    【解决方案2】:

    根据?scales::unit_format,可以设置accuracy = 0.1

    scale_y_continuous(labels = scales::unit_format(
      unit = "k", 
      scale = 1e-3,
      accuracy = 0.1))
    

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多