I would like to remove the redundancy of strip labels when using facet_wrap()
and faceting with two variables and both scales free.
For example, this facet_wrap
version of the following graph
library(ggplot2)
dt <- txhousing[txhousing$year %in% 2000:2002 & txhousing$month %in% 1:3,]
ggplot(dt, aes(median, sales)) +
geom_point() +
facet_wrap(c("year", "month"),
labeller = "label_both",
scales = "free")
should have the looks of this facet_grid
version of it, where the strip labels are at the top and right edge of the graph (could be bottom and left edge as well).
ggplot(dt, aes(median, sales)) +
geom_point() +
facet_grid(c("year", "month"),
labeller = "label_both",
scales = "free")
Unfortunately, using facet_grid
is not an option because, as far as I understand, it doesn't allow scales to be "completely free" - see here or here
One attempt that I thought about would be to produce separate plots and then combine them:
library(cowplot)
theme_set(theme_gray())
p1 <- ggplot(dt[dt$year == 2000,], aes(median, sales)) +
geom_point() +
facet_wrap("month", scales = "free") +
labs(y = "2000") +
theme(axis.title.x = element_blank())
p2 <- ggplot(dt[dt$year == 2001,], aes(median, sales)) +
geom_point() +
facet_wrap("month", scales = "free") +
labs(y = "2001") +
theme(strip.background = element_blank(),
strip.text.x = element_blank(),
axis.title.x = element_blank())
p3 <- ggplot(dt[dt$year == 2002,], aes(median, sales)) +
geom_point() +
facet_wrap("month", scales = "free") +
labs(y = "2002") +
theme(strip.background = element_blank(),
strip.text.x = element_blank())
plot_grid(p1, p2, p3, nrow = 3)
I am ok with the above hackish attempt, but I wonder if there is something in facet_wrap
that could allow the desired output. I feel that I miss something obvious about it and maybe my search for an answer didn't include the proper key words (I have the feeling that this question was addressed before).
See Question&Answers more detail:
os