Reputation: 109
I have a plot of 2 lines representing 2 weeks of data by day (7 days a week), with an additional stat_summary line representing the mean of the 2 lines at the selected interval (day of the week). When I try various methods to add to the legend for the line representing the mean, I get error messages, depending on what solution I'm attempting, from "Insufficient values in manual scale. 2 needed but only 1 provided" or asking if I need to adjust the group aesthetic. Here's the code without attempting to add the mean to the legend, I've simplified to only show two weeks of data to get a reproducible example, my actual code has 5 weeks of data. Right now, it does not seem to matter where I place the 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
I've looked at various answers on SO, but none that I've found so far get me close to a solution of adding "mean" to the legend. I've tried SO answers such as this, that, and other. I'm using ggplot 2.2.0. Thanks!
Upvotes: 0
Views: 841
Reputation: 4761
You could do:
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)
The idea is to integrate the summary function into the main dataframe used to draw the plot. By including it into the aes()
through color=Week
it shows in the legend.
There might be an easier and smarter way with spread/gather.
Upvotes: 1