2017-09-23 43 views
1

我在ggplot中做了一個barplot,並添加了幾行。什麼情況是,該線的顏色和說明不符合:圖例geom_hline的排列順序不正確

enter image description here

黃線應該有說明「中位會員」,但顯示爲「平均會員」。這裏發生了什麼?我使用的代碼:

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

嗨阿爾弗雷德,你可能想在rstudio社區網站上發佈這個問題:https://community.rstudio.com與阿雷克斯更好地幫助他人看到你面臨的問題。 – petergensler

+0

謝謝,不知道那個社區。 – Alfred

回答

0

不要爲要插入的每一行創建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() 

enter image description here

PS:數據您提供沒有意義的兩行重疊。

+0

謝謝,這工作!這樣的代碼也更加整潔。在d1中使用dr代替df時,會出現三行。 Dr =過濾,取3行而不是所有行。 – Alfred