我只是在学习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))))
我希望红色虚线(优先级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")
scale_x_manual()
用于设置值并将图例折叠到一个框中,因此linetype
和color
共享一个图例框,而不是单独的图例框。