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

dar*_*zig 6 r legend ggplot2

ggplot默认情况下,面板下方的图例居中,这在某些情况下确实令人沮丧。请看下面的例子:

ggplot(diamonds, aes(cut, fill = clarity)) + geom_bar() + coord_flip() + 
  theme(legend.position = 'bottom')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

可以看出最后一个标签是从图像中裁剪出来的,尽管我们在图例的左侧有一些空白——使用它会好得多。

:如何将图例居中放置在图下方,而不是试图强制将其居中放置在面板区域下方以解决此问题?


更新:关于这个问题的进一步例子:

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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


我所做的:我可以使用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'))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是这样我必须“手动”计算最佳legend.position. 有什么建议?


更新:我将多个图并排排列,所以我不想将图例放在实际图像上,而是放在单个面板上。例如:

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))
Run Code Online (Sandbox Code Playgroud)

pas*_*asi 7

我正在寻找这个问题的解决方案,并意识到我可以使用Claus Wilke牛图将图分割成网格。这有点麻烦,但很简单。

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)
)
Run Code Online (Sandbox Code Playgroud)

首先,我们将原始绘图保存到一个对象中:

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

接下来,我们将保存它的另一个版本,不带图例,并使用cowplotget_legend()来保存图例:

p2 <- p1 + theme(legend.position = "none")
le1 <- cowplot::get_legend(p1)
Run Code Online (Sandbox Code Playgroud)

画出情节。

cowplot::plot_grid(p2, le1, nrow = 2, rel_heights = c(1, 0.2))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


bap*_*ste 5

您可以编辑 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)
Run Code Online (Sandbox Code Playgroud)