9

我正在安排由 ggplot2 生成的图。我必须使用 print 打印出图和 grid.draw 来显示图例。

示例代码:

p0 <- ggplot(data = iris, geom = 'blank',
         aes(y = Petal.Width, x = Petal.Length, color = Species)) + geom_point() +
      theme(axis.title.x = element_blank(),
            axis.title.y = element_blank(),
            legend.position = "none")

p1 <- ggplot(data = iris, geom = 'blank',
         aes(y = Petal.Length, x = Petal.Width, color = Species)) + geom_point() +
       theme(axis.title.x = element_blank(),
             axis.title.y = element_blank(),
             legend.position = "none")

g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)
}

p <- ggplot(data = iris, geom = 'blank',
        aes(y = Petal.Width, x = Petal.Length, color = Species)) + geom_point()


grid.newpage() 
pushViewport(viewport(layout = grid.layout(2, 4)))
print(p0,vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p0,vp = viewport(layout.pos.row = 1, layout.pos.col = 2:3))
print(p1,vp = viewport(layout.pos.row = 2, layout.pos.col = 2:3))
grid.text("This is x label",gp=gpar(fontsize = 14), vjust = 11,
          vp = viewport(layout.pos.row = 2, layout.pos.col = 2))
grid.text("This is y label",gp=gpar(fontsize = 14), vjust = -11, rot = 90,
          ![enter image description here][1]vp = viewport(layout.pos.row = 2, layout.pos.col = 2))

grid.draw(g_legend(p))

我想把图例放在第四列。我该怎么做?谢谢。

4

3 回答 3

9

在此处输入图像描述使用 gridExtra

         library(gridExtra)
         grid.arrange(p0 , p1,  g_legend(p), ncol=3,
         heights=c(10, 1),widths =c(1,2,1) ,as.table =TRUE)
于 2012-12-04T22:32:24.057 回答
5

您可以手动更改 TableGrob 对象中的 x 和 y 坐标。例如,您可以执行以下操作将图例定位在图的中心:

leg <- g_legend(p)
leg$vp$x <- unit(.5, 'npc')
leg$vp$y <- unit(.5, 'npc')

当您调用 grid.draw(leg) 时,它将被定位在中心。使用不同的值将其放在您喜欢的任何位置。

于 2014-07-12T11:46:49.483 回答
2

在网格中,我们的想法是将视口推到您要绘制的位置,

pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 4))
grid.draw(g_legend(p))

或者,或者,将视口分配给图例 grob,

leg = g_legend(p)
leg$vp = viewport(layout.pos.row = 2, layout.pos.col = 4)
grid.draw(leg)
于 2015-07-26T10:24:14.837 回答