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_blank
ing 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()
Intended plot (approximately):
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")
}