将两个图例放在两行

Pas*_*cal 1 r legend ggplot2

下列

data(iris)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point(aes(shape = Species, colour = Petal.Width)) + 
  theme(legend.position = 'bottom')
Run Code Online (Sandbox Code Playgroud)

将两个图例Petal.WidthSpecies并排放在底部。

我也可以像这样将它们放在一起吗?

例子

我知道这是可能的,cowplot但还有其他方法吗?

kon*_*vas 7

可以通过legend.box内部调整来完成theme(),例如

ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_point(aes(shape = Species, colour = Petal.Width)) + 
    theme(
        legend.justification = 'left', 
        legend.position = 'bottom', legend.box = 'vertical', 
        legend.box.just = 'left')
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

编辑

可以传递许多参数来theme()微调图例之间以及图与图例之间的间距和边距,例如(从 复制?theme

  • legend.margin控制每个图例周围的边距
  • legend.box.margin控制包含所有图例的区域周围的边距
  • legend.spacing, legend.spacing.x,legend.spacing.y控制图例之间的间距

就您而言,如果您的目标是使图例在垂直方向上更紧密地结合在一起,您可以尝试例如legend.margin = margin(-5, 0, 0, 0)