Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot control legend.position in ggplot2 when using facet_wrap()

Tags:

r

ggplot2

In the following code and graphs using mtcars data as example, I try to put the legend at bottom. It works fine without using theme_bw() in the first graph. Once I add theme_bw(), the legend moves to the right. What have I done wrong, and how to fix this? Thanks.

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()

Created on 2020-02-20 by the reprex package (v0.3.0)

like image 619
Zhiqiang Wang Avatar asked Nov 15 '25 04:11

Zhiqiang Wang


1 Answers

You need to reverse the order of theme and theme_bw because theme_bw would override the setting in theme if theme_bw is at the end.

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

like image 96
www Avatar answered Nov 17 '25 19:11

www



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!