0

I want to produce a chart with multiple horizontal facets containing bar charts of varying scales. However, in order to get horizontal facets with a bar chart, I use coord_flip(), but this seems incompatible with horizontal facets (understandably).

How can I have horizontal bar charts arranged in facets? I know I can use grid.arrange or cowplot while manually element_blanking the y-axis. I know I can also use geom_rect as below. Is there a more direct way?

Example data:

library(data.table) ## CJ
library(dplyr)

set.seed(1)

the_dat <- 
  data.table::CJ(
    X = LETTERS[1:5],
    Z = LETTERS[6:8]
  ) %>%
  mutate(Y = ifelse(Z == "G", 
                    # small
                    runif(n()), 
                    rnorm(n(), 100, 50))) 

Using coord_flip() results in the free_x being ignored:

library(ggplot2)

the_dat %>%
  ggplot(aes(x = X, y = Y, fill = Z)) + 
  geom_bar(stat = "identity") +
  facet_grid(~Z, scales = "free") + 
  coord_flip()

enter image description here

Intended plot (approximately):

enter image description here

in which I used a geom_rect hack:

the_dat %>%
  mutate(xf = factor(X)) %>%
  {
  ggplot(., aes(ymin = as.numeric(xf) - 0.35, ymax = as.numeric(xf) + 0.35, 
             xmin = 0, xmax = Y, fill = Z)) + 
  annotate("blank", 
           x = 0, y = unique(.$X)) +
  geom_rect() + 
  facet_grid(~Z, scales = "free")
  }
Hugh
  • 15,521
  • 12
  • 57
  • 100
  • Do you get the expected result without `coord_flip()` ? – mtoto Apr 05 '16 at 10:58
  • Well, no. I see your point. It 'should' be `facet_grid(Z ~., scales = "free")`, but using that with `coord_flip()` gives unmarked y-axes. I thought it was more clear to show that the scales are fixed. The `geom_rect` does show the correct result. – Hugh Apr 05 '16 at 11:02
  • I think using `coord_flip()` in combination with free scales is problematic, because you define a certain axis to be free, then you flip the whole thing. I'd use your workaround with `geom_rect()` if that gives you the expected output. – mtoto Apr 05 '16 at 11:20
  • @Hugh A little late to the party. When I ran your code I get desired graph. Maybe you wanna answer your question. Not sure which version this change was made. – markus Feb 12 '21 at 07:08

0 Answers0