1
votes

I can create a loess line in R, based on a column of dates and a second column of values. Having loaded the dataset, I visualise one column of data below:

scatter.smooth(x=1:length(goals$Value), y=goals$Value)

However, how do I add multiple loess lines for additional columns? What would be the code to plot all the loess lines in one graphic? Say, each additional column is named Value2, Value3, Value4 etc.

2

2 Answers

2
votes

If you haven't yet considered it, the package ggplot2 makes such graphing problems significantly easier to handle, and gives nicer graphs:

library(ggplot2)
library(tidyr)

set.seed(123)
df <- data.frame("days"=1:25, "v1"=rnorm(25), "v2"=(rnorm(25)+0.1))

#Reshape data from wide to long
df2 <- gather(df,var,val,c(v1,v2))

ggplot(df2,aes(x = days, y = val)) +
  geom_point() +
  geom_smooth(aes(colour = var),se = F)

If you don't want to reshape the data, you could add individual lines like this:

ggplot(df,aes(x = days, y = v1)) +
  geom_point() +  #Add scatter plot
  geom_smooth(aes(colour = 'v1'),se = F) +   #Add loess 1
  geom_smooth(aes(y = v2,colour = 'v2'),se = F) +  #Add loess 2... and so on
  scale_colour_discrete(name = 'Line',
                        breaks = c('v1','v2'),
                        labels = c('variable 1','variable 2'))    #Define legend
1
votes

You would used the lines function:

# create test data
set.seed(123)
df <- data.frame("days"=1:25, "v1"=rnorm(25), "v2"=(rnorm(25)+0.1))
# first plot
scatter.smooth(x=df$days, y=df$v1)
# add plot of second lowess line
lines(loess.smooth(x=df$days, y=df$v2))

to add color to the lines:

scatter.smooth(x=df$days, y=df$v1, lpars=list(col="red"))
lines(loess.smooth(x=df$days, y=df$v2), col="green")