图例 geom_hline 顺序不正确

Legend geom_hline not in right order

我在 ggplot 中制作了一个条形图,并添加了几行。发生的情况是线条的颜色和描述不对应:

黄线应具有描述 'Median Member',但显示为 'avg Member'。这里发生了什么?我使用的代码:

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()

不要为要插入的每一行都创建 geom_hline。如果你有一百个怎么办?创建一个单独的对象 d 并在那里指定不同的线型和颜色 geom_hline(data = d, aes(yintercept = value, linetype = name, color = name))。当你想指定颜色时使用: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()

PS.: 您提供的数据没有意义,因为两条线重叠。