Skip to content

different widths in bar plot when using undropped factor levels #5211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
bsgerber opened this issue Feb 28, 2023 · 2 comments · Fixed by #5247
Closed

different widths in bar plot when using undropped factor levels #5211

bsgerber opened this issue Feb 28, 2023 · 2 comments · Fixed by #5247

Comments

@bsgerber
Copy link

bsgerber commented Feb 28, 2023

I found a potential problem with the widths of bars using geom_bar when using factor levels, and keeping unused levels with drop = F argument in scale_x_discrete. This can be overcome by setting the width in aesthetic but thought the variable nature of widths in plotting might be an issue.

Here is the code to reproduce the bug:

library(ggplot2)

df <- data.frame(
  x = factor(c('A', 'D'), levels = LETTERS[1:5])
)

ggplot(df, aes(x)) +
  geom_bar() +
  scale_x_discrete(drop = F)

df <- data.frame(
  x = factor(c('B', 'D'), levels = LETTERS[1:5])
)

ggplot(df, aes(x)) +
  geom_bar() +
  scale_x_discrete(drop = F)

Created on 2023-02-28 with reprex v2.0.2

@teunbrand
Copy link
Collaborator

This is indeed unfortunate. Given that resolution(), which determines the default width, makes a special case for integers; should it also use that case for the "mapped_discrete" class? See:

if (is.integer(x) || zero_range(range(x, na.rm = TRUE)))
return(1)

@thomasp85
Copy link
Member

Yes, I think that is sensible

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants