I am trying to make a simple plot with the following code.
eta = c(0, 0.2, 0.4, 0.6, 0.8, 1)
R = c(0, 0.647058807, 0.864035125, 0.992063541, 0.996376783, 1)
p = as.data.frame(cbind(eta, R))
library(ggplot2)
ggplot(p) +
geom_point(aes(x = eta, y = R), size = 3) +
geom_smooth(aes(y=R, x=eta), method = "loess", se = FALSE)
I get a plot like the following:
Can the geom_smooth function take in arguments to change the line width or line type? Is there a way to get a better fit so that the curve looks like a nice continuous function like the one below?
You can set a custom formula in stat_smooth
. Following your example, if you want to fit a 4th order polynomial you can use
ggplot(p, aes(x = eta, y = R)) +
geom_point(size = 3) +
stat_smooth(method = 'lm', formula = y~ poly(x, 4), se = FALSE)
Edit: Adding an equation that has an asymptote at 1.0. This is a little trickier as it requires solving using a nonlinear approach.
ggplot(p, aes(x = eta, y = R)) +
geom_point(size = 3) +
stat_smooth(method = 'nls',
formula = y ~ 1-exp(-k*x),
se = FALSE)
Although it's convenient for plotting, stat_smooth
makes it tricky to access the fitted model. You can fit outside of ggplot
using the nls
function directly, then make predictions using predict
.
# Fit model
fit_nls <-nls(R ~ 1-exp(-k*eta), data=p)
# Predict model
df_pred <- data.frame(eta = seq(0,1.1,.01)) %>%
mutate(R_pred = predict(fit_nls, newdata = .))
# Plot it
ggplot(p) +
geom_point(aes(x = eta, y = R), size = 3) +
geom_line(data = df_pred, aes(x = eta, y = R_pred))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With