One Weird Trick to Make Ggplot2 Columns the Same Width

[This article was first published on pacha.dev/blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R and Shiny Training: If you find this blog to be interesting, please note that I offer personalized and group-based training sessions that may be reserved through Buy me a Coffee. Additionally, I provide training services in the Spanish language and am available to discuss means by which I may contribute to your Shiny project.

If you have used ggplot2, you probably wondered how to make all columns the same width.

You might have created a plot such as this one.

library(dplyr)
library(ggplot2)

# remotes::install_github("pachadotdev/tintin")
library(tintin)

total_head_trauma_5 <- tintin_head_trauma %>% 
  arrange(-loss_of_consciousness_length) %>% 
  filter(row_number() <= 5)

ggplot(total_head_trauma_5) +
  geom_col(
    aes(
      x = cause_of_injury, y = loss_of_consciousness_length,
      fill = book_title
    ),
    position = "dodge"
  ) +
  labs(
    x = "Cause of injury", y = "Loss of consciousness length",
    title = "Top five causes of injury in Tintin books"
  )

Here’s how to do it with one additional line to the usual ggplot statements.

ggplot(total_head_trauma_5) +
  geom_col(
    aes(
      x = cause_of_injury, y = loss_of_consciousness_length,
      fill = book_title
    ),

    # not this
    # position = "dodge"      
    
    # but this
    position = position_dodge(preserve = "single")
  ) +
  labs(
    x = "Cause of injury", y = "Loss of consciousness length",
    title = "Top five causes of injury in Tintin books"
  )

We can center the columns and make columns in the same category more separated, and also make it a bit nicer.

ggplot(total_head_trauma_5) +
  geom_col(
    aes(
      x = cause_of_injury, y = loss_of_consciousness_length,
      fill = book_title
    ),
    position = position_dodge2(preserve = "single")
  ) +
  labs(
    x = "Cause of injury", y = "Loss of consciousness length",
    title = "Top five causes of injury in Tintin books"
  ) +
  theme_minimal() +
  scale_fill_manual(
    values = tintin_colours$the_black_island, name = "Book"
  ) +
  coord_flip()

To leave a comment for the author, please follow the link and comment on their blog: pacha.dev/blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)