Granite ggplot with a y axis in the middle

Suppose I have two graphs, 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 text of the y axis (for example, 10.0, 7.5, 5.0) in the middle between two graphs? (Preferably, the text should be centered.)

+3
source share
1 answer

Here is the path (well, almost) using the Baptiste answer from this SO post Display the y axis for each subhead during cutting . Not quite in the middle, but 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

+4
source

Source: https://habr.com/ru/post/1538283/


All Articles