r - ggplot2图表轴中的印度风格千位分隔符
问题描述
印度风格的千位分隔符就是这样使用的。第一个分隔符为 3 位数(千位),然后每两位分隔符。
1
10
100
1,000
10,000
1,00,000
10,00,000
1,00,00,000
10,00,00,000
我知道我可以通过使用更改/格式化 ggplot2 图表中的轴scale_y_continuous(labels = scales::comma)
但是如何根据上述印度格式更改 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)
由reprex 包于 2021-06-28 创建 (v2.0.0 )
解决方案
您可以定义自己的格式化函数并将其作为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)
编辑
以下函数使用正则表达式,我认为它更好:
indian_comma <- function(x) {
x <- prettyNum(x, scientific = FALSE)
gsub("(?<!^)(?=(\\d{2})+\\d$)", ",", x, perl = TRUE)
}
推荐阅读
- reactjs - 为什么在全局管理状态时组件内部出现无限循环?
- firebase - [FirebaseError:Firebase:名为“[DEFAULT]”的 Firebase 应用程序已存在(应用程序/重复应用程序)。]
- git - 还原合并还原
- mysql - 为什么我的 MYSQL 事件调度程序每晚午夜停止?
- java - Android PopupWindow dismiss 中途中断涟漪效应
- python - 通过 Python 与 G*Power 通信
- php - Laravel 5.7 中的 digit_between:min, max 是否接受数字类型中允许的符号?
- python - Django Bootstrap Date Picker 默认值/todayBtn 问题
- c# - C# 使用 ClientCertificate 处理客户端请求
- c# - 如何为 Worker 服务安排任务