我在ggplot2中创建了一个1 x 2的数字,并希望将y轴放在图表右侧的其中一个数字上。我差不多了,这是一个MWE,
#Fake data
x = data.frame(
values = c(runif(100, min = -2), runif(100), runif(100, max = 2), runif(100)),
sample = rep(c('sample\na', 'sample\nb'), each = 200),
flag = sample(c('15C', '25C'), 400, replace = TRUE)
)
#Make grobs
p1 = ggplot(subset(x,flag=='15C'),aes(sample,values)) + geom_boxplot() + coord_flip() + facet_wrap(~flag) + theme(axis.title.y=element_blank(),axis.title.x=element_blank())
p2 = ggplot(subset(x,flag=='25C'),aes(sample,values)) + geom_boxplot() + scale_y_reverse() + coord_flip() + facet_wrap(~flag) + theme(axis.title.y=element_blank(),axis.title.x=element_blank(),axis.text.y=element_text(hjust=0))
#Change position of y-axis for p2
g = ggplot_gtable(ggplot_build(p2))
#Find axis grob and make adjustments
ia = which(g$layout$name == "axis_l-1")
ax = g$grobs[[ia]]$children[[2]]
ax$widths = rev(ax$widths)
ax$grobs = rev(ax$grobs)
pp = c(subset(g$layout,name=="panel-1",select=t:r))
g = gtable_add_cols(g,g$widths[g$layout[ia, ]$l],length(g$widths)-1)
g = gtable_add_grob(g,ax, pp$t,length(g$widths)-1,pp$b)
g$grobs[[ia]]$children[[2]] = NULL
g$widths[[3]] = unit(0,'cm')
#Plot it out
windows(height=4,width=8)
grid.draw(cbind(ggplotGrob(p1),g,size='last'))
然而,右侧情节的axis.tick.margin搞砸了(见下图)。我宁愿以某种方式自动化这个。我已经搜索了旧的黑客,但他们似乎已经破坏了升级到ggplot2 v2.0.0。有什么建议吗?