ggplot2 图表轴中的印度风格千位分隔符

Ani*_*yal 3 locale r separator ggplot2

印度风格的千位分隔符就是这样使用的。第一个分隔符为 3 位数字(千),之后每两位数字分隔符。

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
Run Code Online (Sandbox Code Playgroud)

我知道我可以通过使用更改/格式化 ggplot2 图表中的轴 scale_y_continuous(labels = scales::comma)

但是,如何根据上述印度格式更改 r ggplot2 图表轴中的千位分隔符占位符。

示例

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
Run Code Online (Sandbox Code Playgroud)

reprex 包( v2.0.0 )于 2021 年 6 月 28 日创建

Blu*_*oxe 8

您可以定义自己的格式化函数并将其作为labels参数提供给scale_y_continuous(). 下面是一个使用 baseprettyNum()函数的例子:

library(ggplot2)

indian_comma <- function(x) {
  
  # Format the number, first dividing by 10 to place the first comma at the 
  # right point
  out <- prettyNum(x %/% 10, big.interval = 2L, big.mark = ",", scientific = FALSE)
  out <- paste0(out, x %% 10)
  
  # Switch between formatted and un-formatted depending on the size of the
  # number
  ifelse(
    x < 1000, x, out
  )
  
}

iris %>%
  mutate(Petal.Length= Petal.Length*100000) %>%
  ggplot(aes(x= Species, y = Petal.Length)) +
  geom_col() +
  scale_y_continuous(labels = indian_comma)
Run Code Online (Sandbox Code Playgroud)

印度逗号示例

  • 我比我的更喜欢你的函数,除了两件事:我会使用 `x %/% 10` 删除最后一位数字,然后使用 `paste0(x, x %% 10)` 将其放回去。这样,如果有人选择非整数的休息时间,它仍然有效。 (3认同)