如何使用ggplot2将图例放置在绘图的不同侧(底部和右侧)? [英] How to place legends at different sides of plot (bottom and right side) with ggplot2?
本文介绍了如何使用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
所需的绘图(图例应在绘图之外):
推荐答案
利用cowplot
您可以:
- 从没有
linetype
辅助线的绘图中提取color
辅助线,并使用cowplot::get_legend
- 利用
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))
这篇关于如何使用ggplot2将图例放置在绘图的不同侧(底部和右侧)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文