In ggplot2, why are bars not centered on ticks when position is dodged?

In ggplot2, why are bars not centered on ticks when position is dodged?

library(tidyverse)
library(palmerpenguins)
penguins |>
  group_by(species, sex) |> 
  summarise(body_mass_g = mean(body_mass_g)) |>
  ggplot() +
  geom_col(aes(y = body_mass_g, x = species, fill = sex),
    width = 0.9, 
    position = position_dodge(0.9, preserve = "single")
  )

1 Like

This is subtle, but theres a clue in the legend showing an NA, category. Gentoo and Adelie have NA sex entries, which is position dodged would be a column to the rightof the female and male columns. so the bars are centered but you dont see the rightmost bar because not only is its sex NA but the bodymass is NA also so its not drawn.
you can throw in an na.omit() and clear it up

library(tidyverse)
library(palmerpenguins)
penguins |>
  group_by(species, sex) |> 
  summarise(body_mass_g = mean(body_mass_g)) |> na.omit() |> 
  ggplot() +
  geom_col(aes(y = body_mass_g, x = species, fill = sex),
           width = 0.9, 
           position = position_dodge(0.9, preserve = "single")
  )

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.