简体   繁体   中英

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! 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

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. 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. This doesn't have to be a column in data , we can assign any label as a character string. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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