简体   繁体   English

在R分组ggplot2中包括总体平均值

[英]Include overall average in R Grouped ggplot2

I am just learning R and finally have a task at work that I can use it for! 我只是在学习R,最后在工作中有一项我可以使用的任务! However, I am stumped on what I think should be a fairly easy/common thing. 但是,我对我认为应该是一件相当容易/普通的事情感到困惑。

I have this R code that generates the graph below 我有生成下面的图的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图

I would like for the dotted red line (the overall average for the Priority 1 calls) to be included in the legend. 我希望将红色虚线(优先级1通话的总体平均值)包括在图例中。 What do I need to change/add in order for that to be included? 我需要更改/添加什么才能将其包括在内?

Also, is there a way to add a label or text to the vertical lines? 另外,有没有办法在垂直线上添加标签或文本?

To get ggplot to include a geom layer in the legend it needs to have some aes() mapped to it. 为了使ggplot在图例中包括一个geom层,它需要映射一些aes() This doesn't have to be a column in data , we can assign any label as a character string. 这不必是data一列,我们可以将任何标签分配为字符串。 We'll use "average" here: 我们将在此处使用“平均值”:

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

在此处输入图片说明

The scale_x_manual() s are there to set values and to collapse the legends into a single box, so linetype and color share a single legend box, instead of separate ones. scale_x_manual()用来设置值并将图例折叠到单个框中,因此, linetypecolor共享单个图例框,而不是单独的图例框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM