Legend geom_hline not in right order

512 Views Asked by At

I've made a barplot in ggplot, and added a couple of lines. What happens is that the color and description of the lines don't correspond:

enter image description here

The yellow line should have the description 'Median Member', but is displayed as 'avg Member'. What happens here? The code I used:

library(ggplot2)
library(dplyr)

MemberID=c(1,1,1, 2, 2, 2)
ClientCode = c(10,100,1000, 20, 200, 2000)
Duration = c(2356, 1560, 9000, 4569, 3123, 8000)


df <- data.frame(MemberID, ClientCode, Duration)

dr <- df %>%
   filter(MemberID == 1)

dr_avg <- df 

ggplot(dr, aes(reorder(as.character(ClientCode), -Duration), Duration, fill=-Duration)) +
  geom_bar(stat="identity") + # the height of the bar will represent the value in a column of the data frame
  xlab('ClientCode') +
  ylab('Duration (Minutes)') +
  geom_hline(data=dr, aes(yintercept=mean(Duration), linetype = 'Avg Member'), color = 'red', show.legend = TRUE) +
  geom_hline(data=dr, aes(yintercept=median(Duration), linetype = 'Median Member'), color = 'orange', show.legend = TRUE) +
  geom_hline(data=dr_avg, aes(yintercept=mean(Duration), linetype = 'Avg all data'), color = 'blue', show.legend = TRUE) +
  scale_linetype_manual(name = "Line", values = c(2, 2, 2), guide = guide_legend(override.aes = list(color = c("red", "orange", "blue")))) +coord_flip()
1

There are 1 best solutions below

1
On BEST ANSWER

Don't create geom_hline for every line you want to insert. What if you have hundred of them? Create a separate object d and specify different linetypes and colors there geom_hline(data = d, aes(yintercept = value, linetype = name, color = name)). When you want to specify colors use: scale_colour_manual(values = c("red", "orange", "blue")).

d1 <- summarize(df, mean(Duration), median(Duration))
d2 <- summarize(dr_avg, mean(Duration))
d <- data.frame(value = as.numeric(c(d1, d2)), 
               name = c('Avg Member', 'Median Member', 'Avg all data'))

ggplot(dr, aes(reorder(as.character(ClientCode), -Duration), 
               Duration, 
               fill = factor(-Duration))) +
    geom_bar(stat = "identity") + 
    labs(x = "ClientCode",
         y = "Duration (Minutes)") +
    geom_hline(data = d, aes(yintercept = value, linetype = name, color = name)) +
    scale_fill_brewer(palette = "Dark2") +
    scale_colour_manual(values = c("red", "orange", "blue")) +
    coord_flip() +
    theme_bw()

enter image description here

PS.: Data that you provided doesn't make sense as two lines overlap.