Home > Back-end >  Add a legend to a ggplot pointrange figure
Add a legend to a ggplot pointrange figure

Time:07-20

I developed this point range graph and want to add a legend to explain what the black dots (median) and horizontal lines (range) represents as well as what the vertical dashed line (overall median) means.

    data = diamonds %>%
      group_by(cut) %>%
      summarise(min = min(depth), max = max(depth), 
                median = median(depth))
    
    h_line <- 61  
    
    ggplot(data, aes(x = cut, y = median, ymin = min, ymax = max))   
      geom_linerange()   
      geom_hline(yintercept=h_line, linetype="dashed", colour="#0ab58f")  
      geom_pointrange()     coord_flip() 

preview the figure developed

CodePudding user response:

Thanks for clarifying your intended outcome. Here is a potential solution:

library(tidyverse)

data = diamonds %>%
  group_by(cut) %>%
  summarise(min = min(depth), max = max(depth), 
            median = median(depth))

h_line <- 61  

ggplot(data, aes(x = cut, y = median, ymin = min, ymax = max))  
  geom_linerange(aes(linetype = "Range"),
                 key_glyph = "path")  
  geom_hline(aes(yintercept = h_line, colour="#0ab58f"), 
             lty = 2)  
  geom_point(aes(fill = "Median"),
             key_glyph = "point",
             size = 3)  
  coord_flip()  
  scale_fill_discrete(name = "")  
  scale_linetype_discrete(name = "")  
  scale_color_identity(name = "",
                       breaks = "#0ab58f",
                       label = "Group Median",
                       guide = guide_legend())  
  theme(legend.position = "top")

Created on 2022-07-20 by the reprex package (v2.0.1)

  • Related