假设我有两个并排的图,它们具有相同的 y 轴,由以下 R 代码生成:

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

是否可以在两个图之间的中间写入 y 轴文本(例如 10.0、7.5、5.0)? (最好将文本居中。)

最佳答案

这是一种(几乎)使用 Baptiste 来自这篇 SO post Display y-axis for each subplot when faceting 的答案的方法。不完全在中间,但很接近

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)

关于r - 中间有 y 轴的多面 ggplot,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23318411/

10-12 17:09
查看更多