ggplot2:图下方的中心图例,而不是面板区域 [英] ggplot2: center legend below plot instead of panel area
问题描述
ggplot
将图例置于面板下方,这在某些情况下确实令人沮丧.请参见以下示例:
ggplot
by default centers the legend below the panel, which is really frustrating in some situations. Please see the below example:
ggplot(diamonds, aes(cut, fill = clarity)) + geom_bar() + coord_flip() +
theme(legend.position = 'bottom')
可以看到,最后一个标签是从图像中裁剪出来的,尽管图例的左侧有一些空白-使用它会更好.
It can be seen that the last label was cropped from the image, although we have some white-space on the left part of the legend -- it would be a lot better to use that.
问:如何将图例居中放置在图的下方,而不尝试强制将图例居中放置在面板区域的下方,以解决此问题?
Q: how can I center the legend below the plot and not try to force that to be centered below the panel area to overcome this issue?
更新:此问题的进一步示例:
Update: further example on this issue:
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')
我所做的事情:我可以使用legend.direction
手动将图例放在面板下方,并在绘图下方添加一些额外的边距,例如:
What I've done: I can use legend.direction
to manually put the legend below the panel and to add some extra margin below the plot, like:
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'))
但是这种方式我必须手动"计算最佳legend.position
.有什么建议吗?
But this way I have to compute "manually" the optimal legend.position
. Any suggestions?
更新:我正在将多个图并排布置,所以我宁愿不要将图例放在实际图像上居中,而要在单个面板上居中.例如:
Update: I am arranging multiple plots next to each other, so I'd rather not center the legend on the actual image, but rather on the single panel. 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))
推荐答案
您可以编辑gtable,
you can edit the 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)
这篇关于ggplot2:图下方的中心图例,而不是面板区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!