Zhiqiang Wang
Zhiqiang Wang

Reputation: 6759

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

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)

Upvotes: 4

Views: 1117

Answers (1)

www
www

Reputation: 39154

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

Upvotes: 4

Related Questions