3

Suppose I have two plots, side by side, with the same y-axis, generated by the following R code:

df <- data.frame(x=c(5,2,7,3), y=c(11,3,5,6), facet=c(1,1,2,2))
ggplot(df, aes(x, y)) + facet_grid(~facet) + geom_point()

plot

Is it possible to write the y axis text (e.g., 10.0, 7.5, 5.0) in the middle, between the two plots? (Preferentially the text should be centered.)

rodrigorgs
  • 855
  • 2
  • 9
  • 20

1 Answers1

4

Here is a way (well almost) using Baptiste's answer from this SO post Display y-axis for each subplot when faceting. Not quite in the middle but its close

library(ggplot2)
library(gtable)

# your data
df <- data.frame(x=c(5,2,7,3), y=c(11,3,5,6), facet=c(1,1,2,2))

# First plot (a bit of extra space between facets)
p <- ggplot(df, aes(x, y)) + facet_grid(~facet) + 
        geom_point() + 
        theme(panel.margin = unit(1, "lines"),
              axis.text.y  = element_text( hjust=0))

# get y-axis labels 
g <- ggplotGrob(p)
axis <- gtable_filter(g, "axis-l")[["grobs"]][[1]][["children"]][["axis"]][,1]

# remove axis
g[["grobs"]][[4]][["children"]][["axis"]] <- NULL

# build plot & add axis to LHS of left facet
panels <- subset(g$layout, name == "panel")
g <- gtable_add_grob(g, grobs=axis, t = unique(panels$t), l=tail(panels$l, -1)-1)

grid.newpage()
grid.draw(g)

enter image description here

Community
  • 1
  • 1
user20650
  • 24,654
  • 5
  • 56
  • 91
  • Replacing `hjust=0` by `hjust=0.5` centers the text. Also, not in the original question, but is it possible to make it work with `ggsave`? Currently, if I `ggsave(p, file="p.pdf")`, the axis text is not drawn. – rodrigorgs Apr 27 '14 at 10:46
  • 1
    @rodrigorgs; You want to save `g` not `p`. You need a woek around as `ggsave` expects a `ggplot` (not a gtable object). Using Baptistes workaround from here[http://stackoverflow.com/questions/18406991/saving-a-graph-with-ggsave-after-using-ggplot-build-and-ggplot-gtable] ie `ggsave <- ggplot2::ggsave; body(ggsave) <- body(ggplot2::ggsave)[-2]` you can then use `ggsave(grid.draw(g), file="p.pdf")` to produce the plot. – user20650 Apr 27 '14 at 12:17
  • @rodrigorgs; or use `pdf` - that is the what i use (remember to `grid.draw(g)` – user20650 Apr 27 '14 at 12:19
  • Perfect! I noticed it works with `pdf(...)`, `dev.off()`, but I prefer `ggsave(...)` in this case. – rodrigorgs Apr 27 '14 at 12:20
  • @rodrigorgs; great stuff (really all thanks Baptiste's posts) ;) – user20650 Apr 27 '14 at 12:21