Hi:
Here's another approach that doesn't require melting. There is also a
difference between lowess smoothing and loess smoothing, the latter of
which is the default smoother in ggplot2. The game is to create a
factor variable on the fly following the approach shown on p. 106 of
the ggplot2 book.
The data were read into an object named d. The location of the file is
irrelevant but the arguments matter; in particular, it is easier to
convert a character string to a Date object than a factor, which is
why the second argument is present. Then, turn date into a Date object
and add a new variable lowess_y which extracts the y component from
the lowess fit object.
d <- read.csv("../Downloads/weights.csv", header = TRUE,
stringsAsFactors = FALSE)
d$date <- as.Date(d$date, format = '%Y-%m-%d')
d$lowess_y <- with(d, lowess(date, weight))$y
library('ggplot2')
# For each call to geom_line, map colour to a label;
# in this case, "ma" = moving average, "lo" = lowess
# Then use scale_colour_manual() to assign colors
# and legend labels. Note that the "Lowess" label
# comes first because level "lo" precedes level "ma"
# by default when constructing a factor variable, by
# lexicographic ordering.
ggplot(d, aes(x = date)) + geom_point(aes(y = weight)) +
geom_line(aes(y = moving_avg, colour = "ma"), size = 1) +
geom_line(aes(y = lowess_y, color = "lo"), size = 1) +
scale_colour_manual("Type",
values = c("ma" = "blue", "lo" = "orange"),
labels = c("Lowess", "Weighted Moving\nAverage (5 Days)"))
# Same as above, except substituting the default loess fit
# from geom_smooth()
ggplot(d, aes(x = date)) + geom_point(aes(y = weight)) +
geom_line(aes(y = moving_avg, colour = "ma"), size = 1) +
geom_smooth(aes(y = weight, color = "lo"), size = 1, se = FALSE) +
scale_colour_manual("Type",
values = c("ma" = "blue", "lo" = "orange"),
labels = c("Loess", "Weighted Moving\nAverage (5 Days)"))
HTH,
Dennis