Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my line fit better and neater?

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?

like image 420
Outlier Avatar asked Mar 02 '23 13:03

Outlier


1 Answers

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)

enter image description here

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)

enter image description here

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))
like image 113
nniloc Avatar answered Mar 28 '23 14:03

nniloc