私は ggplot2 で 1 x 2 の図を作成しており、図の 1 つの 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 へのアップグレードで壊れたようです。何かアドバイス?