Home > Software design >  Adding a legend when using two layers of geom_col
Adding a legend when using two layers of geom_col

Time:02-22

I have data as follows, to which I would like to simply add a legend (blue means something, red means another thing), for some reason nothing I try even shows up:

Some posts I looked at: enter image description here

CodePudding user response:

If you want to to have a legend for the colors, you have to map it inside of aes() instead of after it in the geom_col(aes()). Afterwards, adjust to your desires using scale_color_identity.

dat %>%
  as_tibble() %>%
  ggplot(aes(x = group_size))  
  geom_col(aes(y = group_sum, color = "red"), position = "identity", fill = "transparent")  
  geom_label(
    data = dat %>% distinct(group_size, .keep_all = TRUE),
    mapping = aes(y = group_sum, label = group_sum), color = "red")  
  geom_col(aes(y = count * 10, color = "blue"), position = "identity", fill = "transparent")  
  geom_label(
    data = dat %>% distinct(count, .keep_all = TRUE),
    mapping = aes(y = count * 10, label = count), color = "blue")  
  scale_y_continuous(sec.axis = sec_axis(trans = ~ . / 10, name = "Count"))  
  labs(color = "Legend")  
  scale_color_identity(name = "Your Legend Name",
                       breaks = c("red", "blue"),
                       labels = c("Your red Name", "Your blue"),
                       guide = "legend")

enter image description here

CodePudding user response:

One option is to put the data into long format and take advantage of ggplot's inbuilt method of determining legends.

library(tidyverse)

count_factor <- 10

dat1 <- 
  dat %>%
  select(-amount) %>% 
  pivot_longer(-group_size, names_to = "var", values_to = "val") %>% 
  distinct() %>% 
  mutate(y = ifelse(var == "group_sum", val/count_factor, val),
         var = fct_rev(var))

dat1 %>%
  ggplot(aes(x = group_size, y = y, colour = var))  
  geom_col(fill = "transparent", position = "identity")  
  geom_label(aes(label = val), show.legend = FALSE)  
  labs(colour = "Legend title") 
  scale_y_continuous(name = "Count", 
                     sec.axis = sec_axis(trans = ~ . * count_factor, name = "Group sum"))

Created on 2022-02-22 by the reprex package (v2.0.1)

  • Related