R 中间有Y轴的GGPOT刻面

R 中间有Y轴的GGPOT刻面,r,ggplot2,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() df这里有一种方法(几乎可以)使用巴普蒂斯特在这篇文章中的答案。不在中间,但接近 library(ggplot2) library(gtable) # your data df <-

假设我有两个并排的图,具有相同的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()
df这里有一种方法(几乎可以)使用巴普蒂斯特在这篇文章中的答案。不在中间,但接近

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)
库(ggplot2)
图书馆(gtable)
#你的数据

df将
hjust=0
替换为
hjust=0.5
使文本居中。另外,不是在原始问题中,但是否可以使其与
ggsave
一起工作?当前,如果I
ggsave(p,file=“p.pdf”)
,则不会绘制轴文本。@rodrigorgs;您想保存
g
而不是
p
。由于
ggsave
需要一个
ggplot
(不是gtable对象),您需要一个woek。从这里使用Baptistes变通方法[ie
ggsave@rodrigorgs;或者使用
pdf
——这就是我使用的方法(记住
grid.draw(g)
Perfect!我注意到它与
pdf(…)
dev.off()
,但我更喜欢
ggsave(…)
,在这种情况下。@rodrigorgs;很棒的东西(真的感谢Baptiste的帖子);)