如何在 ggplot2 中为 geom_text 更改千位分隔符

R.V*_*Van 0 r bar-chart ggplot2 geom-text

我使用 ggplot2 创建了一个条形图,并用它们描绘的值标记了条形图。由于这些值相当大,我想使用千位分隔符。但我想使用倒逗号而不是普通逗号(我已经找到了如何使用逗号分隔)。

我已经尝试以同样的方式来改变 scale_y_continuous 中的千位分隔符,但它没有用。

我还读到我应该使用:

df <- df %>%
  mutate(label.income = gsub("\\,","'", scales::comma(income)))
Run Code Online (Sandbox Code Playgroud)

但是后来我总是收到以下错误消息:“使用方法中的错误(“mutate_”):“mutate_”没有适用的方法应用于“函数”类的对象”

这是我正在使用的数据和代码:

set1 <- read.table(text = "group income
           group1 30500
           group2 29000
           group3 60500
           group4 18000", header=TRUE)

library(ggplot2)
ggplot(set1, aes(x=group, y=income))+
  theme_bw()+
  geom_bar(stat = 'identity', position = "dodge", fill="#13449f")+
  geom_text(aes(label = income), position = position_dodge(0.9), 
        vjust=1.3, colour = "white", size=5)+
  scale_y_continuous(breaks = seq(0, 70000, by = 10000), limits = c(0,70000), labels=function(income) format(income, big.mark = "'", scientific = FALSE))
Run Code Online (Sandbox Code Playgroud)

如何在条形标签上使用与 y 轴上相同的千位分隔符?

小智 6

那是你要的吗 ?

library(ggplot2)
ggplot(set1, aes(x=group, y=income))+
  theme_bw()+
  geom_bar(stat = 'identity', position = "dodge", fill="#13449f")+
  geom_text(aes(label = format(income, big.mark = "'", scientific = FALSE)), position = position_dodge(0.9), 
        vjust=1.3, colour = "white", size=5)+
  scale_y_continuous(breaks = seq(0, 70000, by = 10000), limits = c(0,70000), labels=function(income) format(income, big.mark = "'", scientific = FALSE))
Run Code Online (Sandbox Code Playgroud)