I want to create a ggplot
figure with six panels in R. The first five facets should represent five different subsets of data in bar charts, and the final facet should represent the whole data. I further want to have a fixed y-axis scale across the first five facets, but a different scale in the final facet. I am aware that it is currently not possible to specify individual ylims for each facet within the ggplot functionality (https://github.com/hadley/ggplot2/issues/187), but am wondering if I can do something similar using grid
and possibly gtable
packages, neither of which I'm very familiar with at the moment.
The following is my attempt. I replace the final facet with a facet in another figure.
library("ggplot2")
library("dplyr")
library("grid")
# create data
set.seed(1)
d1 <- data_frame(
value = rnorm(3 * 5, mean = 30, sd = 10),
f = rep(LETTERS[1:3], 5),
p = rep(paste("Panel", 1:5), each = 3)
)
d2 <- d1 %>%
mutate(p = "Total") %>%
rbind(d1)
# make initial figures
plot1 <- ggplot(d2, aes(f, value)) +
geom_bar(stat = "identity") +
facet_wrap(~ p) +
coord_cartesian(ylim = c(0, 50))
plot2 <- ggplot(d2, aes(f, value)) +
geom_bar(stat = "identity") +
facet_wrap(~ p, scales = "free_y")
# extract their grobs
g1 <- ggplotGrob(plot1)
g2 <- ggplotGrob(plot2)
# replace the final facet of plot1 with the final facet of plot2
g1[["grobs"]][[7]] <- g2[["grobs"]][[7]]
g1[["grobs"]][[19]] <- g2[["grobs"]][[19]]
g1[["grobs"]][[25]] <- g2[["grobs"]][[25]]
# draw the figure
grid.newpage()
grid.draw(g1)
And here's what I get.
As can be seen, however, the y-axis label of the final facet overlaps with the preceding facet. Does anyone know a way to avoid the overlap e.g., by making the final facet smaller?
One approach is to extract the "Total" plot from "g2", then insert it into "g1", but first remove the "Total" plot from "g1". But you will notice that the x-axis tick mark labels do not align across the facets.
Another approach is to extract the "Total" plot from "g2" as before, but to move its y-axis to the right side of the plot (using code borrowed from here. (I tweaked your "plot2" so that the tick mark labels are better aligned in the final plot.) In this way, the "Total" panel takes as much space as the other panels, and thus the x-axis tick mark labels align, but the y-axis for the "Total" panel sticks out to the right.