This is in reference to the previous question by @simoncolumbus and answered by @Roland here. I tried to replicate this solution unsuccessfully. I got the error:
"ggplot2 doesn't know how to deal with data of class uneval".
There are several previous posts about this error but in a different context. So please please do not mark this post as duplicate.
I have a data set of 600 respondents. I have an indicator variable with values for each of the 600 respondents across 5 years - 2013, 2014, 2015, 2016, 2017. Also, I have a city column for each respondent. This is a factor variable with 3 levels.
I have created a plot, plotting the indicator trend line for each of the 600 respondents, using 3 colors corresponding to the city the respondent belongs to. The Y-axis is the indicator value and X-axis has years. I have separated the colors of line graphs by cities.
I added 3 median indicator lines, such that there is a median line for respondents for each city. The median lines take the color of the trend lines for each group by default. This is a problem since the median line merges with the individual trend lines, making it difficult to distinguish. I want to use separate colors for median lines, and add this to the legend. I am using the following code:
library(ggplot2)
library(dplyr)
library(tidyr)
library(magrittr)
sample_no <- c(1:600)
city <- c(rep("A",150), rep("B",250), rep("C", 200))
indicator_2013 <- runif(600, min=0, max=1000)
indicator_2014 <- runif(600, min=0, max=1000)
indicator_2015 <- runif(600, min=0, max=1000)
indicator_2016 <- runif(600, min=0, max=1000)
indicator_2017 <- runif(600, min=0, max=1000)
df <- data.frame(sample_no, city, indicator_2013, indicator_2014,
indicator_2015, indicator_2016, indicator_2017)
df1 <- df %>%
gather(indicator_2013, indicator_2014, indicator_2015, indicator_2016, indicator_2017,
key="Year", value = "Indicator")
df1 %>%
ggplot(aes(x=Year, y=Indicator, color=city)) +
geom_line(aes(group = sample_no), alpha = .5, size = 0.7) +
scale_x_discrete(expand = c(0.03, 0.03)) +
labs(col = "City") +
theme(legend.position = c(0.15,0.8), legend.background = element_blank()) +
stat_summary(aes(y = Indicator, group = city),
fun.y=median, geom = "line", linetype="dotted", size = 1,
aes(color = paste("median", city)))
Note: this is only dummy data so graphs are symmetric...
I added code aes(color = paste("median", city))
inside stat_summary to help plot medians in diff colors and add those as the legend along with the legend of individual trend lines but I get the class uneval error. I also tried the scale_color_manual
option outside of stat_summary but that changes the color of individual trend lines as well along with the medians - I need the individual trend line colors to be diff from median lines. Appreciate the help!