How to Add Different Trend Lines in R

How do I add different trend lines in R?

Here's one I prepared earlier:

# set the margins
tmpmar <- par("mar")
tmpmar[3] <- 0.5
par(mar=tmpmar)

# get underlying plot
x <- 1:10
y <- jitter(x^2)
plot(x, y, pch=20)

# basic straight line of fit
fit <- glm(y~x)
co <- coef(fit)
abline(fit, col="blue", lwd=2)

# exponential
f <- function(x,a,b) {a * exp(b * x)}
fit <- nls(y ~ f(x,a,b), start = c(a=1, b=1))
co <- coef(fit)
curve(f(x, a=co[1], b=co[2]), add = TRUE, col="green", lwd=2)

# logarithmic
f <- function(x,a,b) {a * log(x) + b}
fit <- nls(y ~ f(x,a,b), start = c(a=1, b=1))
co <- coef(fit)
curve(f(x, a=co[1], b=co[2]), add = TRUE, col="orange", lwd=2)

# polynomial
f <- function(x,a,b,d) {(a*x^2) + (b*x) + d}
fit <- nls(y ~ f(x,a,b,d), start = c(a=1, b=1, d=1))
co <- coef(fit)
curve(f(x, a=co[1], b=co[2], d=co[3]), add = TRUE, col="pink", lwd=2)

Add a descriptive legend:

# legend
legend("topleft",
legend=c("linear","exponential","logarithmic","polynomial"),
col=c("blue","green","orange","pink"),
lwd=2,
)

Result:

Sample Image

A generic and less long-hand way of plotting the curves is to just pass x and the list of coefficients to the curve function, like:

curve(do.call(f, c(list(x), coef(fit)) ), add=TRUE)

How to build a trendline on a graph in R

since you had some data points missing, I took what you had provided: the six points.

edit - now the full example was available

  1. A trendline is just a regression, and regressions are run most simple way like this:
    a<-lm(outcome~predictor) -- in this example the object a will hold your regression parameters. To get the values of your new trendline model, just use predict(model_name), or in your case predict(a)

  2. Adding line to a plot is dead simple. Just say lines(b), where b specifies the line you want to plot after you have used the plot() function.

To wrap it up:

[![myds <- c(23.0415,13.1965,10.4110,12.2560,9.5910,10.7160,9.9665,8.5845,8.9855,8.8920,10.3425,9.3820,9.0860,9.6870,8.5635,9.0755,8.5960,7.9485,8.3235,8.1910)
x <- (1:length(myds))
plot(myds)

#make the main plot
plot(x,myds,ylim=c(5,30),xlim=c(0,20))

#add linear trend
lines(predict(lm(myds~x)),col='green')

#one more trend
lines(predict(lm(myds~log(x))),col='red')][1]][1]

resulting plot image

How do I add multiple traces/trendlines each with a subset of data onto a single scatterplot in R using plotly

The easiest way to do this would be within ggplot itself, using geom_smooth to do the regression for you:

lawn <- ggplot(dat, aes(x=CWD, y=Lawn, colour=factor(Year))) + 
geom_point() +
geom_smooth(method = 'lm', se = FALSE)

Note that I've name the data dat, since data is a function in R.

With you sample data:

Sample Image

In regards to color, have a look at ?scale_colour_discrete.

Adding two separate trend lines for specific time period in ggplot

You can use geom_segment:

geom_segment(aes(x=..., y=..., xend=..., yend=...))

You just have to replace with the values you want your line to start and stop.

Edit: with your data, that will do something like

ggplot(sns1, aes(x = date, y = metric_value)) +
geom_line(size = 1, color = "#E41A1C") +
geom_segment(aes(x= 11/14/2020, y=20.6, xend=12/26/2020, yend=21.5))+
geom_segment(...)

With the same idea for the second line.

Is it possible to draw multiple trendlines within a single time series graph in ggplot2?

You can simply repeat your geom_smooth call with subsets of the original data frame:

ggplot(data, aes(x = Year, y = SPM)) +
geom_line(color = 'black', size = 1.3) +
geom_point(color = "blue", size = 1.3) +
stat_smooth(method = "lm", formula = y ~ x, size = 0.75, se = TRUE,
color = "blue", fill = "#9AE5D7") +
stat_smooth(method = "lm", formula = y ~ x, size = 0.75, se = TRUE,
color = "red", fill = "red", alpha = 0.2,
data = data[data$Year < as.Date("2009-06-01"),]) +
stat_smooth(method = "lm", formula = y ~ x, size = 0.75, se = TRUE,
color = "forestgreen", fill = "forestgreen", alpha = 0.2,
data = data[data$Year >= as.Date("2009-06-01"),]) +
stat_poly_eq(face = "bold", parse = TRUE, aes(label = ..eq.label..),
formula = y ~ x, label.x.npc = 0.5, label.y.npc = 0.1,
size = 6, coef.digits = 4) +
stat_fit_glance(method = 'lm', method.args = list(formula = y ~ x),
geom = 'text',
aes(label = paste(
"P-value = ", signif(..p.value.., digits = 4), sep = ""
)), size = 6, label.x = "left", label.y = "top") +
scale_x_date(date_labels = "%Y", date_breaks = "1 year") +
labs(x = "Time (Years)", y = "Concentration") +
theme_bw() +
theme(plot.title = element_text(size = 17, face = "bold"),
axis.title.x = element_text(size = 20, face = "bold"),
axis.title.y = element_text(size = 20, face = "bold"),
axis.text.x = element_text(size = 18, face = "bold"),
axis.text.y = element_text(size = 18, face = "bold"),
strip.text.x = element_text(size = 16, face = "bold"),
strip.text.y = element_text(size = 16, face = "bold"),
axis.line.x = element_line(color = "black", size = 1),
axis.line.y = element_line(color = "black", size = 1),
axis.ticks = element_line(color = "black", size = 1.2),
axis.ticks.length = unit(0.2, "cm"),
panel.border = element_rect(fill = NA, size = 1),
legend.title = element_blank(),
legend.position = c(.8, .2))

Sample Image

In this case, the overall trend is fairly constant, so the background blue line is obscured by the two partial segments.

How do you add trendline to part of data in ggplot2?

Similar to both above just using subset:

ggplot(data1, aes(x, y = value, color = name))+ 
geom_point()+
geom_smooth(data=subset(data1, x > 3), method = 'lm',se = FALSE)

Sample Image



Related Topics



Leave a reply



Submit