Number formatting in labels in ggplot2?

I tried to format the labels that appears above of each column. I want them to have a thousand separator. It could be a comma or a point.

This is the code that I have tried.

df%>%
  group_by(Hour)%>%
  summarize(TotalValue= round(sum(Value)/1000000))%>%
  ggplot(aes(x = Hour, y = TotalValue, fill = "coral4"))+
  scale_x_continuous(breaks = seq(7,22,1))+
  scale_y_continuous(labels = comma)+
  geom_col()+
  theme_bw()+
  theme(legend.position = "none")+
  geom_label_repel(aes(label = TotalValue),
                   box.padding   = 0.35,
                   point.padding = 0.5,
                   segment.color = 'grey50')

This is plot the plot generated by the previous code

What I want is, for example, in the third column (valor = 37692) the number should has this format 36,792

Upvotes: 0

Views: 901

Answers (1)

Tim Hargreaves
Tim Hargreaves

Reputation: 332

You can use the format() function. An example:

labels <- c(43252, 54326, 54325)
format(labels, big.mark = ',', scientific = FALSE)
#> [1] "43,252" "54,326" "54,325"

In your example it would become:

df%>%
  group_by(Hour)%>%
  summarize(TotalValue= round(sum(Value)/1000000))%>%
  ggplot(aes(x = Hour, y = TotalValue, fill = "coral4"))+
  scale_x_continuous(breaks = seq(7,22,1))+
  scale_y_continuous(labels = comma)+
  geom_col()+
  theme_bw()+
  theme(legend.position = "none")+
  geom_label_repel(aes(label = format(TotalValue, 
                                      big.mark = ',',
                                      scientific = FALSE)),
                   box.padding   = 0.35,
                   point.padding = 0.5,
                   segment.color = 'grey50')

You can use ?format to read more.

Upvotes: 1

Related Questions