Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bolding geom_text() and including thousands separator in R

Tags:

r

ggplot2

I have the following ggplot code.

mpg %>%
  ggplot2::ggplot(ggplot2::aes(x = as.character(class))) +
  ggplot2::geom_bar(fill = '#00798c')  +
  ggplot2::geom_text(stat = "count", ggplot2::aes(label = after_stat(count)), position = ggplot2::position_dodge(width = 0.8), vjust = -0.3) 

How can I make the geom_text() annotations bold and also have a thousands comma separator?

I have been looking at the documentation and not really sure how I can do this?

I tried using scales::comma(count) nested inside the after_stat() but I got an error. No idea how to bold annotated text after reading the documentation.

like image 254
Eisen Avatar asked Sep 17 '25 20:09

Eisen


2 Answers

Not sure what's your issue. scales::comma works fine for me. To get bold labels add fontface="bold":

Note: As the values are too small I multiplied by 1000 so that we get a thousands separator.

library(ggplot2)

ggplot(mpg, aes(x = class)) +
  geom_bar(fill = '#00798c')  +
  geom_text(stat = "count", aes(label = after_stat(scales::comma(1000 * count))), 
            position = position_dodge(width = 0.8), 
            vjust = -.3, fontface = "bold")

like image 63
stefan Avatar answered Sep 20 '25 12:09

stefan


scales::comma() is now superseded by scales::label_number().

The syntax is a bit different. There is no x argument as before. The call to label_number() creates a function. Then the after_stat is fed to this function.

Using the example by stefan, it would be:

library(ggplot2)

ggplot(mpg, aes(x = class)) +
geom_bar(fill = '#00798c')  +
geom_text(stat = "count", 
          aes(label = scales::label_number(scale = 1000, big.mark = ",")(after_stat(count))),
          position = position_dodge(width = 0.8), 
          vjust = -.3, fontface = "bold")
like image 21
Marc-Antoine L Avatar answered Sep 20 '25 12:09

Marc-Antoine L