使用facet_wrap()时,无法控制ggplot2中的图例位置。

3
在以下使用mtcars数据作为示例的代码和图表中,我尝试将图例放置在bottom。在第一个图中不使用theme_bw()可以正常工作。一旦我添加了theme_bw(),图例就会移到右边。我做错了什么,如何修复?谢谢。
library(tidyverse)
mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am)
             )
         ) + 
  geom_boxplot() + 
  facet_wrap(vars(vs)) +
  theme(legend.position = "bottom", 
        legend.title = element_blank()) 

mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am))) + 
  geom_boxplot() + 
  facet_wrap(vars(vs)) +
  theme(legend.position = "bottom", 
        legend.title = element_blank()) +
  theme_bw()

本文创建于2020年2月20日,使用reprex包 (v0.3.0)


@camille 是的。回头看,这算是同样的问题,但对于用户来说很难识别两者之间的联系。 - Zhiqiang Wang
1个回答

3

由于theme_bw如果放在最后会覆盖theme的设置,因此您需要颠倒themetheme_bw的顺序。

library(ggplot2)
library(magrittr)

mtcars %>%
  ggplot(aes(x = factor(cyl), y = mpg,
             color = factor(am))) + 
  geom_boxplot() + 
  facet_wrap(vars(mtcars$vs)) +
  theme_bw() +
  theme(legend.position = "bottom", 
        legend.title = element_blank())

enter image description here


1
太好了,谢谢。我之前没有想到过,但现在有意义了。 - Zhiqiang Wang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接