zoowalk
zoowalk

Reputation: 2134

ggplot: how to get same bar widths across different facets

I regularly have to create plots similar to the one below. What somewhat annoys me with the result is the location and the size/(bin)width of the bar in the facet B.

Ideally, I would like to have the bar positioned on the same level/height as the bar of c in facet A and the two remaining 'spaces' (where a and b are located in facet A) remain empty in facet B.

library(tidyverse)

df <- tibble::tribble(
  ~group, ~unit, ~value,
     "A",   "a",    10L,
     "A",   "b",    15L,
     "A",   "c",    20L,
     "A",   "c",    25L,
     "B",   "d",    10L
  )

df %>% 
  ggplot()+
  geom_bar(aes(x=unit,
               y=value),
           stat="identity")+
  facet_wrap(vars(group),
             scales = "free_y")+
  coord_flip()

Created on 2020-05-26 by the reprex package (v0.3.0)

I am aware that I can use scales="free" or use patchwork, cowplot package etc. But as far as I can tell, none of these approaches would yield the desired result.

Any idea? Many thanks!

Upvotes: 1

Views: 819

Answers (1)

Axeman
Axeman

Reputation: 35392

Only way I can think of is to hard-code the widths of the bars:

ggplot(df, aes(x = unit, y = value))+
  geom_col(width = c(0.9, 0.9, 0.9, 0.9, 0.35)) +
  facet_wrap(vars(group), scales = 'free_y')+
  coord_flip()

enter image description here

Upvotes: 2

Related Questions