5

I try to drop the legend by setting show.legend = FALSE. It works as expected when the fill variable is discrete:

library(ggplot2)
ggplot(mtcars, aes(x = mpg, y = wt, fill = factor(mpg))) +
  geom_bar(stat = "identity", show.legend = FALSE)

enter image description here However, when fill is mapped to a continuous variable, show.legend = FALSE does not drop the legend:

ggplot(mtcars, aes(x = mpg, y = wt, fill = mpg)) + 
   geom_bar(stat = "identity", show.legend = FALSE) 

enter image description here

Why doesn't show.legend = FALSE omit the legend for a continuous scale? How can I solve this?

I have ggplot2 v.2.0.0 (author: Hadley Wickham)

Reference: http://docs.ggplot2.org/current/geom_bar.html

Henrik
  • 65,555
  • 14
  • 143
  • 159
PatrickT
  • 10,037
  • 9
  • 76
  • 111
  • Does anyone think this is a bug? – PatrickT Mar 03 '16 at 23:51
  • 1
    `show.legend` works for a discrete scale though; `ggplot(mtcars, aes(mpg, wt, fill = factor(mpg))) + geom_bar(stat = "identity", show.legend = FALSE)`. That it doesn't work for a continuous scale seems like a bug (or an undocumented feature...). Same in the recently released `ggplot2_2.1.0`. – Henrik Mar 04 '16 at 07:15
  • 1
    I posted [an issue](https://github.com/hadley/ggplot2/issues/1568). – Henrik Mar 04 '16 at 07:54
  • 1
    Thanks for the edit and feedback Henrik! – PatrickT Mar 04 '16 at 13:12

1 Answers1

8

For your example case, you can use theme()

ggplot(mtcars, aes(mpg, wt, fill = mpg)) + 
  geom_bar(stat = "identity") +
  theme(legend.position = 'none')
arvi1000
  • 9,393
  • 2
  • 42
  • 52
  • Thanks. Interesting: if you add ``+ theme_bw()`` after ``theme(legend.position = 'none')``, the legend reappears. (I knew about ``legend.position`` but hadn't tested it on my MWE and my systematic use of ``theme_bw()`` at the end of my code reintroduced the legend). Edit: I should have known better. – PatrickT Mar 03 '16 at 23:50
  • 3
    that's because adding `theme_bw()` _afterwards_ cancels out the settings you apply in `theme()`. Add `+ theme_bw()` first and `+ theme(legend.position = 'none')` next, and you should be good – arvi1000 Mar 04 '16 at 01:51
  • This actually also fix it when piping your ggplot to `plotly::ggplotly` ignores the `show.legend = FALSE` argument. – cbo May 14 '20 at 15:12