我正在尝试绘制一个包含两个图例的图,一个位于图的底部,另一个位于图的右侧。
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)
所需的情节(图例应位于情节之外):
利用cowplot你可以做到:
color从没有指南的图中提取指南linetype并legend.position = "right"使用cowplot::get_legendcowplot::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)
