MikeRSpencer
MikeRSpencer

Reputation: 1316

ggplot2 - Turn off legend for one geom with same aesthetic as another geom

I'm making a plot with two different geoms, both use fill. I'd like one geom to have a legend, but the other to not. However adding show.legend=F to the required geom doesn't switch off the legend for that geom.

Example:

library(tidyverse)
library(ggalluvial)

x = tibble(qms = c("grass", "cereal", "cereal"),
           move1 = "Birth",
           move2 = c("Direct", "Market", "Slaughter"),
           move3 = c("Slaughter", "Slaughter", NA),
           freq = c(10, 5, 7))

x %>% 
  mutate(id = qms) %>% 
  to_lodes_form(axis = 2:4, id = id) %>% 
  na.omit() %>% 
  ggplot(aes(x = x, stratum = stratum, alluvium = id,
             y = freq, label = stratum)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = qms)) +
  geom_stratum(aes(fill = stratum), show.legend=F) +
  geom_text(stat = "stratum", size = 3) +
  theme_void() +
  labs(fill="")

Output:

Output from code

Desired output:

Desired output

Question:

How do I turn off the fill legend for one geom, but not the other? I can (if I have to) do this in inkscape/gimp, but would prefer a solution I can version control.

Upvotes: 4

Views: 510

Answers (1)

Dan
Dan

Reputation: 12084

Have a look at the final line of code:

scale_fill_discrete(breaks = c("grass", "cereal")) 

That defines the breaks for the fills to only include cereal and grass, as required.

library(tidyverse)
library(ggalluvial)

x = tibble(qms = c("grass", "cereal", "cereal"),
           move1 = "Birth",
           move2 = c("Direct", "Market", "Slaughter"),
           move3 = c("Slaughter", "Slaughter", NA),
           freq = c(10, 5, 7))

x %>% 
  mutate(id = qms) %>% 
  to_lodes_form(axis = 2:4, id = id) %>% 
  na.omit() %>% 
  ggplot(aes(x = x, stratum = stratum, alluvium = id,
             y = freq, label = stratum)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow(aes(fill = qms)) +
  geom_stratum(aes(fill = stratum), show.legend=FALSE) +
  geom_text(stat = "stratum", size = 3) +
  theme_void() +
  labs(fill="") +
  scale_fill_discrete(breaks = c("grass", "cereal")) #<- This line!

Created on 2019-03-18 by the reprex package (v0.2.1)

Upvotes: 3

Related Questions