Skip to content

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

Closed

Description

@bsgerber

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

Activity

  1. teunbrand commented on Feb 28, 2023

    @teunbrand
    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)

  2. thomasp85 commented on Mar 13, 2023

    @thomasp85
    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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions