5

I'm trying to remove the 'n' legend from the following plot. I'm guessing it's related to the stat part of geom_bar() but am not entirely sure what it is showing and hence am not sure how to remove it. I do want the fill legend so show.legends=FALSE isn't the right option. Sorry if this is a duplicate but after a lot of looking I can't find the answer, changing the legend on a scale_x_x doesn't cover it.

ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width,fill=Species))+
   geom_bar(stat="sum")

enter image description here

Morgan Ball
  • 760
  • 9
  • 23
  • 1
    Possible duplicate of [Turning off some legends in a ggplot](https://stackoverflow.com/questions/14604435/turning-off-some-legends-in-a-ggplot) – kath Aug 22 '18 at 11:13
  • I looked at this one @kath but it's not what is needed here – Morgan Ball Aug 22 '18 at 11:17
  • 3
    You can add `+ guides(size = F)` to you plot, so yes it is not exactly there only `guides(color = F)` – kath Aug 22 '18 at 11:21
  • Thanks kath that's perfect. The issue I was having was identifying it was the size element that was causing the issue, which James has helped with below – Morgan Ball Aug 22 '18 at 11:22

2 Answers2

11

You can control legends with the show.legend parameter, with fine control by using a named vector:

show.legend

logical. Should this layer be included in the legends? NA, the default, includes if any aesthetics are mapped. FALSE never includes, and TRUE always includes. It can also be a named logical vector to finely select the aesthetics to display.

The trick is to recognise that the n part of the legend comes from the size aesthetic.

ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width,fill=Species))+
+    geom_bar(stat="sum", show.legend=c(size=FALSE))
James
  • 65,548
  • 14
  • 155
  • 193
3

I would do the following

library(tidyverse)
iris %>%
    group_by(Species, Sepal.Length) %>%
    summarise(Sepal.Width = sum(Sepal.Width)) %>%
    ggplot(aes(Sepal.Length, Sepal.Width, fill = Species)) +
    geom_col()

enter image description here

Explanation: Summarise Sepal.Width per Species per Sepal.Length first, then plot. Generally (I think) it is advisable and tidier to keep data manipulations/summarisations and plotting separate.

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68