2

我正在 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 被搞砸了(见下图)。我宁愿以某种方式自动化它。我已经搜索过旧的 hack,但它们似乎已经在升级到 ggplot2 v2.0.0 时中断了。有什么建议吗?

在此处输入图像描述

4

0 回答 0