Show Sidebar Hide Sidebar # stat_smooth in ggplot2

Add a smoothed line in ggplot2 and R with stat_smooth.

### New to Plotly?

Plotly's R library is free and open source!
You can set up Plotly to work in online or offline mode.
We also have a quick-reference cheatsheet (new!) to help you get started!

### Version Check

Version 4 of Plotly's R package is now available!
Check out this post for more information on breaking changes and new features available in this version.

library(plotly)
packageVersion('plotly')

##  '4.9.1'


### Basic

library(plotly)

p <- ggplot(mpg, aes(displ, hwy))
p <- p + geom_point() + stat_smooth()

p <- ggplotly(p)

p


Inspired by ggplot2 documentation

### Trend Lines

library(plotly)

x <- 1:10
y <- jitter(x^2)

DF <- data.frame(x, y)

p <- ggplot(DF, aes(x = x, y = y)) + geom_point() +
stat_smooth(method = 'lm', aes(colour = 'linear'), se = FALSE) +
stat_smooth(method = 'lm', formula = y ~ poly(x,2), aes(colour = 'polynomial'), se= FALSE) +
stat_smooth(method = 'nls', formula = y ~ a * log(x) +b, aes(colour = 'logarithmic'), se = FALSE, start = list(a=1,b=1)) +
stat_smooth(method = 'nls', formula = y ~ a*exp(b *x), aes(colour = 'Exponential'), se = FALSE, start = list(a=1,b=1))

p <- ggplotly(p)

p


Inspired by Stack Oveflow

### Facetgrid

library(plotly)

x <- rnorm(100)
y <-  + .7*x + rnorm(100)
f1 <- as.factor(c(rep("A",50),rep("B",50)))
f2 <- as.factor(rep(c(rep("C",25),rep("D",25)),2))
df <- data.frame(cbind(x,y))
df$f1 <- f1 df$f2 <- f2

p <- ggplot(df,aes(x=x,y=y)) +
geom_point() +
facet_grid(f1~f2) +
stat_smooth(method="lm")

p <- ggplotly(p)

p


Inspired by Stack Overflow

library(plotly)
set.seed(123)

x <- rnorm(1000)
y1 <- 2*x + rnorm(1000)
y2 <- x^2 + rnorm(1000)

ds <- data.frame(data = x,
Linear = y1,

cols1 <- c("#ff8080", "#66b3ff")
cols2 <- c("#ff4d4d", "#3399ff")

p <- ggplot(ds, aes(x = data)) +
geom_point(aes(y = Linear, color = "Linear"), size = 2, alpha = 0.5) +
geom_point(aes(y = Quadratic, color = "Non Linear"), size = 2, alpha = 0.5) +
stat_smooth(aes(x = data, y = Linear, linetype = "Linear Fit"), method = "lm", formula = y ~ x, se = F, size = 0.25, color = cols2) +
stat_smooth(aes(x = data, y = Quadratic, linetype = "Quadratic Fit"), method = "lm", formula = y ~ poly(x,2), se = F, size = 0.25, color = cols2) +
scale_color_manual(name = "Relationship", values = c(cols1, cols1)) +
scale_linetype_manual(name = "Fit Type", values = c(2, 2)) +
ggtitle("Manual Legend for Stat Smooth")

p <- ggplotly(p)

p


Inspired by Stack Overflow 