Continuous baseline for faceted plots

Is there any way in ggplot2 to draw a continuous baseline across multiple facets? The closest I have found is to add a geom_hline to the plot. I would like the horizontal line to be continuous across all transmission types below.

Thanks,
Kent

library(ggplot2)

ggplot(mpg, aes(class, fill=class)) + 
  geom_hline(yintercept=0) +
  geom_bar() + 
  facet_grid(cyl~trans, switch='x') +
  theme_minimal() +
  theme(axis.ticks=element_blank(),
  axis.text.x=element_blank(),
  panel.grid=element_blank()) +
  labs(x='')

Created on 2018-10-05 by the reprex package (v0.2.0).

1 Like

Firstly, thanks for posting a simple reprex that gets to the point!

You can "connect" the baselines by removing the spaces between facets in each row.

library(ggplot2)

ggplot(mpg, aes(class, fill=class)) + 
  geom_hline(yintercept=0) +
  geom_bar() + 
  facet_grid(cyl~trans, switch='x') +
  theme_minimal() +
  theme(
    axis.ticks=element_blank(),
    axis.text.x=element_blank(),
    panel.grid=element_blank(),
    panel.spacing.x = unit(0, "null")  # no horizontal space between panels
  ) +
  labs(x='')

5 Likes

This is an incomplete answer, but given @nwerth's lovely, simple solution I won't spend more time on it.

My thought was to start with something like this:

ggplot(mpg, aes(trans, fill=class)) + 
   geom_bar(position='dodge') + 
   facet_wrap(~cyl,ncol=1) +
   theme_minimal() +
   theme(axis.ticks=element_blank(),
   panel.grid=element_blank()) +
   labs(x='')

The problem with this is that there are unrepresented levels of class leading to variable width bars. I think there was another post about handling that recently. You could calculate the summary before plotting, such that all combinations of trans and class are represented (ie with 0 where necessary) then do the above with stat='identity' for geom_bar. I think.

Thank you @nwerth. I want to maintain some separation between the groups - my actual data is considerably more dense than the example. Adding scale_x_discrete(expand=expand_scale(add=1)) does the trick!

library(ggplot2)

ggplot(mpg, aes(class, fill=class)) + 
  geom_hline(yintercept=0) +
  geom_bar() + 
  facet_grid(cyl~trans, switch='x') +
  theme_minimal() +
  theme(axis.ticks=element_blank(),
  axis.text.x=element_blank(),
  panel.spacing.x = unit(0, "null"),
  panel.grid=element_blank()) +
  labs(x='') +
  scale_x_discrete(expand=expand_scale(add=1))

Created on 2018-10-05 by the reprex package (v0.2.0).

2 Likes