firmo23
firmo23

Reputation: 8404

Add commas between numbers in label and legend of ggplot2 plot

I have the dataframe below and I create a boxplot. I would like to format the numbers in y-axis and legend in order to have commas or .

df_long<-structure(list(WORDS = c("Comedy", "Education", "Entertainment", 
"Film & Animation", "Gaming", "Howto & Style", "Music", "People & Blogs", 
"Science & Technology", "Sports"), TOTALS = c(0, 943330388, 0, 
0, 0, 543234645, 45831420, 0, 27301292, 160818771)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

p <- ggplot(df_long, aes(x = WORDS, y = TOTALS, fill = WORDS)) + 
  geom_boxplot()

p  +  
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, 
                                   hjust=1))+ 
  xlab("Industries") +
  ylab("Value")+ guides(fill=guide_legend(title="Industries"))
+
  scale_y_continuous(formatter = comma)+scale_fill_continuous(formatter = comma)

Upvotes: 2

Views: 1533

Answers (1)

Peter
Peter

Reputation: 12699

One way is using scales::comma.

Note I've removed scale_fill_continuous as this is incorrect: the fill aesthetic relates to a discrete variable: WORDS

library(ggplot2)
library(scales)

ggplot(df_long, aes(x = WORDS, y = TOTALS, fill = WORDS)) + 
  geom_boxplot()  +  
  theme_minimal()+ 
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, 
                                   hjust=1))+ 
  xlab("Industries") +
  ylab("Value")+ 
  guides(fill = guide_legend(title="Industries")) +
  scale_y_continuous(labels = comma)

Created on 2022-03-21 by the reprex package (v2.0.1)

Upvotes: 4

Related Questions