44

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

enter image description here

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.

Community
  • 1
  • 1
Drew Steen
  • 16,045
  • 12
  • 62
  • 90
  • Is this right?: You are looking to have x-axis labels only on the bottom row of the panels, and you would like those labels to extend into the empty panel space at row two column three. – metasequoia Nov 08 '12 at 20:36
  • 2
    The issue has now been fixed in the development version of ggplot2. See ggplot2 issue #1607: [X axis doesn't appear below facet_wrap plot with uneven number of facets](https://github.com/hadley/ggplot2/issues/1607) – Paul Rougieux Sep 21 '16 at 07:01

1 Answers1

61

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 (see getAnywhere(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 and ncol anymore, plots with all the panels can be printed too.

library(grid)
# pos - where to add new labels
# newpage, vp - see ?print.ggplot
facetAdjust <- function(x, pos = c("up", "down"), 
                        newpage = is.null(vp), vp = NULL)
{
  # part of print.ggplot
  ggplot2:::set_last_plot(x)
  if(newpage)
    grid.newpage()
  pos <- match.arg(pos)
  p <- ggplot_build(x)
  gtable <- ggplot_gtable(p)
  # finding dimensions
  dims <- apply(p$panel$layout[2:3], 2, max)
  nrow <- dims[1]
  ncol <- dims[2]
  # number of panels in the plot
  panels <- sum(grepl("panel", names(gtable$grobs)))
  space <- ncol * nrow
  # missing panels
  n <- space - panels
  # checking whether modifications are needed
  if(panels != space){
    # indices of panels to fix
    idx <- (space - ncol - n + 1):(space - ncol)
    # copying x-axis of the last existing panel to the chosen panels 
    # in the row above
    gtable$grobs[paste0("axis_b",idx)] <- list(gtable$grobs[[paste0("axis_b",panels)]])
    if(pos == "down"){
      # if pos == down then shifting labels down to the same level as 
      # the x-axis of last panel
      rows <- grep(paste0("axis_b\\-[", idx[1], "-", idx[n], "]"), 
                   gtable$layout$name)
      lastAxis <- grep(paste0("axis_b\\-", panels), gtable$layout$name)
      gtable$layout[rows, c("t","b")] <- gtable$layout[lastAxis, c("t")]
    }
  }
  # again part of print.ggplot, plotting adjusted version
  if(is.null(vp)){
    grid.draw(gtable)
  }
  else{
    if (is.character(vp)) 
      seekViewport(vp)
    else pushViewport(vp)
    grid.draw(gtable)
    upViewport()
  }
  invisible(p)
}

And here is how it looks

d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
  xlim(0, 2) + stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) + 
  facet_wrap(~ color)
facetAdjust(d)

enter image description here

facetAdjust(d, "down")

enter image description here

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 with facetAdjust. A plot of class of ggplot is required because of two parts in the source code of ggsave: print(plot) and default_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 use class(gtable) <- c("facetAdjust", "gtable", "ggplot"). In this way, it is allowed to use ggsave and print(plot) works as required (see below for print.facetAdjust)

facetAdjust <- function(x, pos = c("up", "down"))
{
  pos <- match.arg(pos)
  p <- ggplot_build(x)
  gtable <- ggplot_gtable(p); dev.off()
  dims <- apply(p$panel$layout[2:3], 2, max)
  nrow <- dims[1]
  ncol <- dims[2]
  panels <- sum(grepl("panel", names(gtable$grobs)))
  space <- ncol * nrow
  n <- space - panels
  if(panels != space){
    idx <- (space - ncol - n + 1):(space - ncol)
    gtable$grobs[paste0("axis_b",idx)] <- list(gtable$grobs[[paste0("axis_b",panels)]])
    if(pos == "down"){
      rows <- grep(paste0("axis_b\\-[", idx[1], "-", idx[n], "]"), 
                   gtable$layout$name)
      lastAxis <- grep(paste0("axis_b\\-", panels), gtable$layout$name)
      gtable$layout[rows, c("t","b")] <- gtable$layout[lastAxis, c("t")]
    }
  }
  class(gtable) <- c("facetAdjust", "gtable", "ggplot"); gtable
}

The function for printing which differs only by few lines from ggplot2:::print.ggplot:

print.facetAdjust <- function(x, newpage = is.null(vp), vp = NULL) {
  if(newpage)
    grid.newpage()
  if(is.null(vp)){
    grid.draw(x)
  } else {
    if (is.character(vp)) 
      seekViewport(vp)
    else pushViewport(vp)
    grid.draw(x)
    upViewport()
  }
  invisible(x)
}

Example:

d <- ggplot(diamonds, aes(carat, price, fill = ..density..)) +
  xlim(0, 2) + stat_binhex(na.rm = TRUE) + theme(aspect.ratio = 1) + 
  facet_wrap(~ color)
p <- facetAdjust(d) # No output
print(p) # The same output as with the old version of facetAdjust()
ggsave("name.pdf", p) # Works, a filename is necessary
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
  • Very nice! You should have waited a day, I was going to offer a bounty. – Drew Steen Nov 09 '12 at 21:27
  • 7
    @DrewSteen, ouch.. Well, I'll consider this function as a bounty. Definitely going to use it myself. – Julius Vainora Nov 09 '12 at 21:44
  • @DrewSteen: you can still offer a bounty, and give it directly to Julius. – naught101 May 27 '13 at 06:37
  • @Julius, That is a great function. The only problem that I have is, that I can't save the image with the ggsave function anymore. Is there some way to save it with ggsave? pdf() doesn't offer some of the functions I need... :-/ – Dominik Jun 01 '13 at 12:30
  • @Dominik, I have updated my answer with an alternative solution – Julius Vainora Jun 01 '13 at 15:04
  • 4
    @Julius, That is pretty amazing! Thanks for this. Can't you ask Hadley to add this funktion in ggplot2 natively? I think a lot of persons would like to have this... – Dominik Jun 02 '13 at 12:00
  • @Dominik, this is only a workaround and wouldn't fit in `ggplot2` since it ruins some things, e.g. it neglects some classes and uses a new one. I'd guess that Hadley is aware of such a request, but seems that you could post it [here](https://github.com/hadley/ggplot2/issues?labels=feature&page=1&state=open) as well. – Julius Vainora Jun 02 '13 at 16:56
  • @Julius Has this feature been requested [there](https://github.com/hadley/ggplot2/issues?labels=feature&page=1&state=open)? Any change since this answer was posted? – Paul Rougieux Apr 08 '16 at 09:58
  • @PaulRougieux, I am not aware of such a request. Another reason to believe that there were no changes would be that I keep getting upvotes for this answer. – Julius Vainora Apr 08 '16 at 10:13
  • 1
    I posted an issue on github.com/hadley/ggplot2: [X axis doesn't appear below facet_wrap plot with uneven number of facets](https://github.com/hadley/ggplot2/issues/1607). – Paul Rougieux Apr 08 '16 at 12:00
  • 2
    [This issue](https://github.com/hadley/ggplot2/issues/1607) has now been fixed in the development version of ggplot2. I'll post this comment also just below the question above. – Paul Rougieux Sep 21 '16 at 06:59