Search code examples
rggplot2graphlinebar-chart

ggplot: How to add a group average value as a line to a grouped bar chart in R?


I would like to add the "All_Parties_average" value to my bar chart as a green line with a legend (see the second picture added by a link). Really appreciate the help!

Right now my graph looks like this:

My graph at the moment

This is kind of what I would like it to look like:

End result

Here is my data:

Gender <- as.factor(c("M","M","M","M","M","M","M","M","M","M","F","F","F","F","F","F","F","F","F","F"))
Political_Party <- as.factor(c("E200", "EKRE", "ERE", "Isamaa", "REF","Roh", "SDE", "Vabae", "Vasak", "KE","E200", "EKRE", "ERE", "Isamaa", "REF","Roh", "SDE", "Vabae", "Vasak", "KE"))
Media_coverage_average <- c(61,95,41,162,107,23,130,68,6,152,99,49,9,87,157,52,112,31,14,202)
All_Parties_average <- c(90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90)

my_data <- data.frame(Sugu, Political_Party, Media_coverage_average, All_Parties_average, stringsAsFactors=F)  

Also colors for the graph:

my_colors <- c(
  `Green` <- "#00a99d",
  `Purple` <- "#9424fb",
  `Grey` <- "#a6a6a6",
  `LightPurple` <- "#c991fd",
  `LightGrey` <- "#c9c9c9",
  `DarkGrey`<- "#636363",
  `ExtraDarkGrey`<- "#4c4c4c")

And my graph:

my_plot <- ggplot(my_data, aes(x = Political_Party, y = Media_coverage_average, fill = Gender))+
  geom_bar(position="dodge", stat="identity")+
  geom_text(aes(label=Media_coverage_average), position=position_dodge(width=0.9), vjust=-0.25, size=6, family="Titillium Web", color= ExtraDarkGrey)+
  labs(x="Political Party", y="Average media coverage",
       caption = "Author")+
  theme_ipsum_tw(grid=FALSE, axis_text_size=18, axis_title_size = 16, caption_size = 15, base_size = 17, subtitle_size = 20)+
  scale_fill_manual(values = c(Grey, Purple), labels = c("Mehed", "Naised"))

my_plot


Solution

  • Additionaly to @Senzeybek's answer, you can add a legend for the green line by passing its color into the aes of geom_line and setting the color by using scale_color_manual:

    library(ggplot2)
    ggplot(my_data, aes(x = Political_Party, y = Media_coverage_average, fill = Gender))+
      geom_bar(position="dodge", stat="identity")+
      geom_text(aes(label=Media_coverage_average), position=position_dodge(width=0.9), vjust=-0.25, size=6, family="Titillium Web", color= ExtraDarkGrey)+
      labs(x="Political Party", y="Average media coverage",
           caption = "Author")+
      #theme_ipsum_tw(grid=FALSE, axis_text_size=18, axis_title_size = 16, caption_size = 15, base_size = 17, subtitle_size = 20)+
      scale_fill_manual(values = c(Grey, Purple), labels = c("Mehed", "Naised"))+
      geom_hline(aes(yintercept = All_Parties_average, color = "Average", group = 1), size = 2)+
      scale_color_manual(values = "green")
    

    enter image description here