如何使用 ggplot2 将图例放置在图的不同侧面(底部和右侧)?

Alv*_*les 6 plot r ggplot2

我正在尝试绘制一个包含两个图例的图,一个位于图的底部,另一个位于图的右侧。

library(tidyverse)

df <- tibble(names = mtcars %>% 
  rownames(),
  mtcars)

#plot 1
p1 <- df %>% 
  filter(names == "Duster 360" | names == "Valiant") %>% 
ggplot(aes(x = as.factor(cyl), y = mpg, color = names)) +
  geom_point() +
  geom_hline(aes(yintercept = 20, linetype = "a")) +
  theme(legend.position = "bottom")

p1
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

所需的情节(图例应位于情节之外):

在此输入图像描述

ste*_*fan 4

利用cowplot你可以做到:

  1. color从没有指南的图中提取指南linetypelegend.position = "right"使用cowplot::get_legend
  2. 利用cowplot::plot_grid制作一个具有两列的网格,其中第一列包含没有指南的绘图color,并且linetype指南放置在底部,而color指南则放置在第二列中。
library(tidyverse)

df <- tibble(names = mtcars %>% 
               rownames(),
             mtcars)

p1 <- df %>% 
  filter(names == "Duster 360" | names == "Valiant") %>% 
  ggplot(aes(x = as.factor(cyl), y = mpg, color = names)) +
  geom_point() +
  geom_hline(aes(yintercept = 20, linetype = "a"))

library(cowplot)

guide_color <- get_legend(p1 + guides(linetype = "none"))

plot_grid(p1 + 
            guides(color = "none") + 
            theme(legend.position = "bottom"), 
          guide_color, 
          ncol = 2, rel_widths = c(.85, .15))
Run Code Online (Sandbox Code Playgroud)