将stat_summary行添加到现有图例

时间:2017-01-13 16:55:33

标签: r ggplot2 legend

我有一个2行的图表,表示每天2天的数据(每周7天),另外的stat_summary行表示所选间隔(一周中的一天)的2行的平均值。当我尝试使用各种方法添加到代表均值的行的图例时,我会收到错误消息,具体取决于我正在尝试的解决方案,“手动缩放中的值不足。需要2个但只提供1个”或者询问我是否需要调整群体美感。这里的代码没有尝试将平均值添加到图例中,我已经简化为仅显示两周的数据以获得可重现的示例,我的实际代码有5周的数据。现在,我放置scale_color_manual的位置似乎并不重要。

    library(ggplot2)
    cbPalette <- c("#E69F00", "#56B4E9", "#009E73", "#0072B2",
                   "#D55E00", "#999999")
    col1 <- rep(c("Monday", "Tuesday", "Wednesday",
              "Thursday", "Friday", "Saturday",
              "Sunday"), 2)
    col2 <- c(rep(1, 7), rep(2, 7))
    col3 <- c(9446,7681,11576,6788,11782,8414,7011,5321,5418,5533,6123,6924,12420,6313)
    activitySleep <- data.frame(cbind(col1, col2, col3),
                                stringsAsFactors = FALSE)
    colnames(activitySleep) <- c("DayOfWeek", "Week", "Steps")
    activitySleep$DayOfWeek <- factor(activitySleep$DayOfWeek,
                                      levels = c("Monday", "Tuesday", "Wednesday",
                                         "Thursday", "Friday", "Saturday",
                                         "Sunday"))
    activitySleep$Steps <- as.integer(activitySleep$Steps)
    p1 <- ggplot(activitySleep, mapping = aes(x = DayOfWeek, y = Steps,
                                              color = Week)) +
      geom_line(aes(group = Week), lwd = 1.25) +
      ggtitle("Step Tracker") +
      theme(plot.title = element_text(hjust = 0.5)) +
      xlab("Day of the Week") +
      ylab("Number of Steps") +
      scale_color_manual(values = cbPalette)
    p1a <- p1 + stat_summary(fun.y = mean, geom = "line", color = "#999999",
                             aes(group = 1), lwd = 1.25) 
    p1a

我已经看过SO上的各种答案,但到目前为止我找不到任何答案让我接近一个为传奇添加“意思”的解决方案。我尝试了thisthatother等答案。我正在使用ggplot 2.2.0。谢谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做:

library(tidyverse)
df=bind_rows(activitySleep,activitySleep%>%group_by(DayOfWeek)%>%summarise(Steps=mean(Steps)))
df=replace_na(df,list(Week="mean"))
ggplot(df, mapping = aes(x = DayOfWeek, y = Steps,color = Week)) +
  geom_line(aes(group = Week), lwd = 1.25) +
  ggtitle("Step Tracker") +
  theme(plot.title = element_text(hjust = 0.5)) +
  xlab("Day of the Week") +
  ylab("Number of Steps") +
  scale_color_manual(values = cbPalette)

这个想法是将摘要函数集成到用于绘制图的主数据框中。将其包含在图例中显示的aes()color=Week中。 enter image description here
传播/聚集可能有一种更简单,更智能的方式。