Skip to content

Default width of geom_bar/geom_col under facetting #4336

Closed

Description

@hutch3232

params$width %||% (resolution(data$x, FALSE) * 0.9)

^ This line shows how the default width for geom_bar and geom_col is selected as "By default, set to 90% of the resolution of the data." I recently came across a situation where I was making a facetted column chart and the resolution of the data (across all groups) was very small. So small, that I could not see the columns. Manually setting the width solved the issue until I realized what was happening. The resolution within groups was much larger. I'm suggesting it may be better to compute the resolution for each group, then perhaps take the minimum resolution.

This should illustrate the issue:

> library(tidyverse)
-- Attaching packages ------------------------------------------------------------------------------------------------------------------------ tidyverse 1.3.0 --
v ggplot2 3.3.3     v purrr   0.3.4
v tibble  3.0.6     v dplyr   1.0.3
v tidyr   1.1.2     v stringr 1.4.0
v readr   1.4.0     v forcats 0.5.1
-- Conflicts --------------------------------------------------------------------------------------------------------------------------- tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag()    masks stats::lag()

I start by creating a tibble where the resolution without considering group is 0.1.

my_tibble <- tibble(x = c(1.5, 2.5, 3.5,
                          1.6, 2.6, 3.6),
                    y = c(10, 9, 8,
                          20, 19, 18),
                    group = rep(c("a", "b"), each = 3))

> resolution(x = my_tibble$x, zero = FALSE)
[1] 0.1

Then making my facetted plot creates strangely narrow columns. I believe this should illustrate the problem. If the values within each group have a reasonable resolution for plotting, but the resolution of all data is very narrow plots look funny (or in my real-data case, do not show up at all).

ggplot(data = my_tibble, mapping = aes(x = x, y = y, fill = group)) +
  geom_col() +
  facet_grid(cols = vars(group))

image

Here is one possible way to determine a more appropriate width:

desired_width <- 0.9*my_tibble %>% 
  group_by(group) %>% 
  summarise(res = resolution(x = x, zero = FALSE)) %>% 
  select(res) %>% 
  min()

> desired_width
[1] 0.9

Overriding the default width provides a more natural ggplot.

image

Activity

  1. added
    feature
    on Mar 24, 2021
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

    featurelayers 📈

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions