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

问题描述 投票:0回答:3

印度风格的千位分隔符是这样使用的。第一个分隔符位于 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)

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

r ggplot2 locale separator
3个回答
9
投票

您可以定义自己的格式化函数并将其作为

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 <- function(x) {
  x <- prettyNum(x, scientific = FALSE)
  gsub("(?<!^)(?=(\\d{2})+\\d$)", ",", x, perl = TRUE)
}

2
投票

可以设置y轴的分隔符,然后按照印度系统进行标注:

iris %>%
    mutate(Petal.Length= Petal.Length*100000) %>%
    ggplot(aes(x= Species, y = Petal.Length)) +
    geom_col() +
    scale_y_continuous(breaks = c(0,10000000,20000000),labels = c("0","1,00,00000","2,00,00,000"))

2
投票

这篇文章:https://stackoverflow.com/a/62037466/2554330定义了一个函数

format2()
。它不能按原样工作,但是通过一些小的修复,就可以工作了:

format2 <- function(x, ..., big.mark = "", big.interval = c(3L, 2L), decimal.mark = ".") {
  intervene <- !is.na(x) && x > 0 && (log(abs(x), 10) >= sum(big.interval)) && nzchar(big.mark)
  cl <- match.call()
  cl[[1]] <- substitute(format)
  if (intervene) {
    cl$x <- x %/% 10^big.interval[1]
    cl$big.interval <- big.interval[2]
    bigx <- eval.parent(cl)
    cl$x <- x 
    cl$big.interval <- big.interval[1]
    mostx <- eval.parent(cl)
    mostx <- 
      substr(mostx,
             1L + nchar(x %/% 10^big.interval[1]) +
               trunc(trunc(log(abs(x %/% 10^big.interval[1]), 10L)) / big.interval[1]),
             nchar(mostx))
    return( paste0(bigx, mostx) )
  } else eval.parent(cl)
}

f <- function(x) {
  sapply(x, format2, scientific = FALSE, big.mark = ",")
}

library(tidyverse)
iris %>%
  mutate(Petal.Length= Petal.Length*100000) %>%
  ggplot(aes(x= Species, y = Petal.Length)) +
  geom_col() +
  scale_y_continuous(labels = f)

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

© www.soinside.com 2019 - 2024. All rights reserved.