R.Van
R.Van

Reputation: 127

How to change the thousand-separator in ggplot2 for geom_text

I have created a bar plot using ggplot2 and I have labeled the bars with the values they depict. Since these values are rather large, I would like to use thousand separators. But I want to use an inverted comma instead of a regular comma (I already found out how to separate using commas).

I already tried to do it the same way one can change the thousand separators in scale_y_continuous but it didn't work.

I also read that I should use:

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

But then I always get the following error message: "Error in UseMethod("mutate_") : no applicable method for 'mutate_' applied to an object of class "function""

This is the data and code I am using:

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))

How can I have the same thousand separators on the labels in the bars as I have on the y-axis?

Upvotes: 0

Views: 6337

Answers (1)

lemairev
lemairev

Reputation: 216

is that what you want ?

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))

Upvotes: 8

Related Questions