rodrigorgs
rodrigorgs

Reputation: 875

Faceted ggplot with y axis in the middle

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

Upvotes: 3

Views: 1361

Answers (1)

user20650
user20650

Reputation: 25854

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

Upvotes: 4

Related Questions