I have the same problem as this user - I have a 'jagged' faceted plot, in which the bottom row has fewer panels than the other rows, and I would like to have x-axis ticks on the bottom of each column.
The suggested solution for that problem was to set scales="free_x"
. (In ggplot 0.9.2.1; I believe the behavior I'm looking for was default in earlier versions.) That's a poor solution in my case: my actual axis labels will be rather long, so putting them under each row will occupy too much room. The results are something like this:
x <- gl(3, 1, 15, labels=paste("this is a very long axis label ", letters[1:5]))
y <- rnorm(length(x))
l <- gl(5, 3, 15)
d <- data.frame(x=x, y=y, l=l)
ggplot(d, aes(x=x, y=y)) + geom_point() + facet_wrap(~l, scales="free_x") +
theme(axis.text.x=element_text(angle=90, hjust=1))
In a comment here, Andrie suggests that it can be done manually in grid
but I have no idea how to get started on that.
If I remember right, there were questions on both how to add all labels to the same line under the last column and how to lift these last labels up to the next row. So here is the function for both cases:
Edit: since this is like a substitute for
print.ggplot
(seegetAnywhere(print.ggplot)
) I have added some lines from it to preserve functionality.Edit 2: I have improved it a bit more: no need to specify
nrow
andncol
anymore, plots with all the panels can be printed too.And here is how it looks
Edit 3:
This is an alternative solution, the one above is fine as well.
There are some issues when one wants to use
ggsave
together withfacetAdjust
. A plot of class ofggplot
is required because of two parts in the source code ofggsave
:print(plot)
anddefault_name(plot)
in case one does not provide a filename manually (according to?ggsave
it seems that it is not supposed to work, though). Hence, given a filename, there is a workaround (possibly with side effects in some cases):First, let us consider the separate function that achieves the main effect of floating axis. Normally, it would return a
gtable
object, however we useclass(gtable) <- c("facetAdjust", "gtable", "ggplot")
. In this way, it is allowed to useggsave
andprint(plot)
works as required (see below forprint.facetAdjust
)The function for printing which differs only by few lines from
ggplot2:::print.ggplot
:Example: