r - 中间有 y 轴的多面 ggplot

标签 r ggplot2

假设我有两个并排的图,具有相同的 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()

plot

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

最佳答案

这是一种(差不多)使用 Baptiste 在这篇 SO 帖子 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)

enter image description here

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

相关文章:

r - 创建一个PDF表格

r - 在 ggplot2 中堆积条形图的顶部显示每组的总(和)值

r - 使用 coord_fixed 进行多图布局

r - 使用 geom_smooth 进行对数插值

r - ggplot 到 ggplotly 不适用于自定义的 geom_boxplot 宽度

r - Ggplot 不显示源函数中的绘图

r - 如何在 knitr 和 RStudio 中为 word 和 html 设置不同的全局选项?

r - 如何访问/复制 View 功能?

r - 我如何才能发现Rscript已由CWL在docker上成功运行?

r - 从 R 中的点绘制热图