1

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

在此处输入图像描述

黄线应该有描述“中值成员”,但显示为“平均成员”。这里会发生什么?我使用的代码:

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

1 回答 1

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

在此处输入图像描述

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

于 2017-09-23T16:10:10.643 回答