Horizontal bar chart with facets

2019-08-28 19:17发布

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")
  }

标签: r ggplot2
0条回答
登录 后发表回答