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

标签 r ggplot2 locale separator

Indian style thousand separators像这样使用。第一个分隔符为 3 位数字(千),之后每两位数字分隔符。

1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
我知道我可以使用 scale_y_continuous(labels = scales::comma) 更改/格式化 ggplot2 图表中的轴
但是,如何根据上述印度格式更改 r ggplot2 图表轴中的千位分隔符占位符。
示例
library(tidyverse)
iris %>%
  mutate(Petal.Length= Petal.Length*100000) %>%
  ggplot(aes(x= Species, y = Petal.Length)) +
  geom_col() +
  scale_y_continuous(labels = scales::comma)

创建于 2021-06-28 由 reprex package (v2.0.0)

最佳答案

您可以定义自己的格式化函数并将其提供为 labels论据 scale_y_continuous() .这是一个使用基础 prettyNum() 的示例功能:

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)
Indian comma example
编辑
以下函数使用正则表达式,我认为它更好:
indian_comma <- function(x) {
  x <- prettyNum(x, scientific = FALSE)
  gsub("(?<!^)(?=(\\d{2})+\\d$)", ",", x, perl = TRUE)
}

关于r - ggplot2 图表轴中的印度风格千位分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68160094/

相关文章:

r - Ubuntu 16.04 R 安装 : configure: gdal-config not found or not executable

r - xgboost:线性 boost 器 gblinear 中使用了哪些参数?

r - 使用 ggplot2 绘制圆形密度图

android - 如何更改另一个应用程序的语言环境?

c++ - 文件名如何在 `char` 和 2 字节字符之间工作?

r - 多项式混合 logit 模型 mlogit r-package

r - ggplot2 : multiple factors boxplot with scale_x_date axis in R

r - 在 ggplot stat_smooth 调用后可以提取模型拟合参数吗?

r - 在一系列 fiddle 图上绘制趋势线

java - 在java中将字符串转换为日期