如何使用ggplot2将图例放置在绘图的不同侧(底部和右侧)? [英] How to place legends at different sides of plot (bottom and right side) with ggplot2?

查看:5
本文介绍了如何使用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您可以:

  1. 从没有linetype辅助线的绘图中提取color辅助线,并使用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))

这篇关于如何使用ggplot2将图例放置在绘图的不同侧(底部和右侧)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆