Home > Blockchain >  ggplot: adding a legend entry for a line to a grouped bar chart
ggplot: adding a legend entry for a line to a grouped bar chart

Time:01-31

I'd like to plot, in R and using ggplot2, a bar chart displaying, for several groups, two variables as bars and one variable as a line. All variables are on the same scale.

Using diamonds as an example,

library(tidyverse)

diamonds %>% 
    group_by(cut) %>% 
    summarize(avg = median(carat), min = min(carat), max = max(carat)) %>%
    pivot_longer(cols = c("min", "max"), names_to = "bounds", values_to = "weight") %>%
    ggplot()  
    geom_col(mapping = aes(x = cut, y = weight, fill = bounds), position = "dodge")  
    geom_line(mapping = aes(x = cut, y = avg), group = 1)

gives

enter image description here

What I'd now like to do is two-fold:

  1. add a legend entry for the line; and
  2. ideally also control the color for the line.

I've searched both google and SO, as well as looked at scale_color_*, but without success, and I'm still not really "grokking" ggplot2's idiosyncratic approach to plotting, so any help would be appreciated. Thanks!

CodePudding user response:

You could add a color to the aesthetic to get a legend for the line and use scale_color_manual to change the color line like this:

library(tidyverse)

diamonds %>% 
  group_by(cut) %>% 
  summarize(avg = median(carat), min = min(carat), max = max(carat)) %>%
  pivot_longer(cols = c("min", "max"), names_to = "bounds", values_to = "weight") %>%
  ggplot()  
  geom_col(mapping = aes(x = cut, y = weight, fill = bounds), position = "dodge")  
  geom_line(mapping = aes(x = cut, y = avg, color = "name_line"), group = 1)  
  scale_color_manual("Legend line", values = c("name_line" = "yellow"))

Created on 2023-01-27 with reprex v2.0.2

  • Related