ggplot2:中心图例下方的图而不是面板区域

时间:2014-08-02 22:41:10

标签: r ggplot2 legend

默认情况下,

ggplot将图例置于面板下方,这在某些情况下非常令人沮丧。请参阅以下示例:

ggplot(diamonds, aes(cut, fill = clarity)) + geom_bar() + coord_flip() + 
  theme(legend.position = 'bottom')

enter image description here

可以看出最后一个标签是从图像中裁剪出来的,虽然我们在图例的左侧部分有一些白色空间 - 使用它会好得多。

:如何将图例置于图表下方,不要试图强制它在面板区域下方居中以克服此问题?


更新:有关此问题的进一步示例:

df <- data.frame(
    x = sample(paste('An extremely long category label that screws up legend placement', letters[1:7]), 1e3, TRUE),
    y = sample(paste('Short label', letters[1:7]), 1e3, TRUE)
    )

ggplot(df, aes(x, fill = y)) + geom_bar() + coord_flip() +
  theme(legend.position = 'bottom')

enter image description here


我做过的事情:我可以使用legend.direction手动将图例放在面板下方,并在图表下方添加一些额外的边距,例如:

ggplot(diamonds, aes(cut, fill = clarity)) + geom_bar() + coord_flip() + 
  theme(legend.position  = c(0.37, -0.1),
        legend.direction = 'horizontal',
        plot.margin      = grid::unit(c(0.1,0.1,2,0.1), 'lines'))

enter image description here

但是这种方式我必须手动计算&#34;最优legend.position。有什么建议吗?


更新:我正在将多个地块排列在一起,所以我不希望将图例放在实际图像上,而是放在单个面板上。 E.g:

p1 <- ggplot(diamonds, aes(cut)) + geom_histogram()
p2 <- ggplot(diamonds, aes(cut, fill = clarity)) + geom_bar() + coord_flip() +
  theme(legend.position = 'bottom')
pushViewport(viewport(layout = grid.layout(nrow = 1, ncol = 2, widths = unit(c(1, 2), c("null", "null")))))
print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
print(p2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))

2 个答案:

答案 0 :(得分:2)

你可以编辑gtable,

library(gtable)

g <- ggplotGrob(p)
id <- which(g$layout$name == "guide-box")
g$layout[id, c("l","r")] <- c(1, ncol(g))
grid.newpage()
grid.draw(g)

答案 1 :(得分:2)

我正在寻找这个问题的解决方案,并意识到我可以使用Claus Wilke&#39; cowplot将绘图分割成网格。这有点像黑客但很容易。

df <- data.frame(
  x = sample(paste('An extremely long category label that screws up legend placement', letters[1:7]), 1e3, TRUE),
  y = sample(paste('Short label', letters[1:7]), 1e3, TRUE)
)

首先让原始绘图保存到对象:

p1 <- ggplot(df, aes(x, fill = y)) + geom_bar() + coord_flip() +
  theme(legend.position = 'bottom')

接下来我们将在没有图例的情况下保存它的另一个版本,并使用cowplot&#39; get_legend()来保存图例:

p2 <- p1 + theme(legend.position = "none")
le1 <- cowplot::get_legend(p1)

画出情节。

cowplot::plot_grid(p2, le1, nrow = 2, rel_heights = c(1, 0.2))

enter image description here