包括R Grouped ggplot2中的总体平均值

时间:2017-12-05 14:38:38

标签: r ggplot2

我只是在学习R,最后还有一项工作任务,我可以用它!但是,我对我认为应该是一件相当容易/普通的事情感到困惑。

我有这个R代码生成下面的图表

ggplot(data = subset(AverageHoldingTimes, CallPriority==1 & AverageCreatedToDispatct > 0 & CallCreatedHour %in% c(0,1,2,3,4,5,6,7)), mapping = aes(x=CallDate, y=AverageCreatedToDispatct)) + 
  geom_smooth(se = FALSE, mapping = aes(color = AreaCommand)) + 
  geom_smooth(se = FALSE, linetype = 2, color='red') +
  geom_vline(xintercept = as.POSIXct(as.Date(c("2016-09-15", "2017-08-15"))), linetype=4) +
  labs(y = "Average Number of Minutes to Dispatch", title = "Priority 1 Call Average Number of Minutes to Dispatch Midnight To 8 AM", x = "Call Date") + 
  scale_colour_hue(name="Area Command", labels=c("FootHills", "NorthEast", "NorthWest", "SouthEast", "SouthWest", "Valley"), guide = guide_legend(override.aes = list(linetype = c(1, 1, 1, 1, 1, 1))))

R graph

我希望红色虚线(优先级1调用的总体平均值)包含在图例中。我需要更改/添加什么才能包含它?

另外,有没有办法在垂直线上添加标签或文字?

1 个答案:

答案 0 :(得分:0)

要让ggplot在图例中包含geom图层,需要将一些aes()映射到它。这不必是data中的列,我们可以将任何标签指定为字符串。我们将使用"平均值"这里:

ggplot(mtcars, aes(wt, mpg)) +
  geom_smooth(se = FALSE, aes(color = as.factor(cyl), linetype = as.factor(cyl))) +
  geom_smooth(se = FALSE, aes(group = NULL, color = "average", linetype = "average")) +
  scale_color_manual(values = c("red","green","blue","black"), name = "Area Command") +
  scale_linetype_manual(values = c(1,1,1,3), name = "Area Command")

enter image description here

scale_x_manual()用于设置值并将图例折叠到一个框中,因此linetypecolor共享一个图例框,而不是单独的图例框。