Search code examples
rggplot2curve

Saturation curve in ggplot


I tried to fit my data with the loess and lm method (ggplot2) before, however none of these methods are a good fit. Now I am trying to fit a saturation curve to the data, but cannot find a way to do this. After googling a while, I wonder if this is even possible using ggplot2. Otherwise I thought about fitting a logistic regression, and have tried this, which unforunatley gives me the following error:

This produces the wanted graph with the loess method. How can I plot this with a saturation curve?

specprec <- ggplot(data=master, aes(prec_average, binomial_c))+
  geom_point(size=1.3, shape=16)+
  theme_bw(base_size = 14)+
  theme(aspect.ratio=1)+
  labs(x="Mean precipitation", y="Species richness")+
  stat_smooth(method="loess")

Here's how I tried to fit a logistic regression curve:

m <- glm(prec_average ~ binomial_c, family = gaussian, data = master)
p_specprec <-  augment(m, type.predict = "response")
head(p_specprec)
 
 base <-
   ggplot(p_specprec, aes(x = prec_average, y=m)) +#   geom_line(aes(y = m), color = "blue") +
   labs(x = "Mean precipitation", y = "Species richness")

Error: Don't know how to automatically pick scale for object of type glm/lm. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (4538): y

Any hints would be of great help! Thanks in advance!


Solution

  • The error comes because you are trying to plot the model m rather than a column from the dataframe p_specprec.

    Since I don't have access to your data, I've used mtcars and relabeled some of the columns.

    library(ggplot)
    master <- mtcars
    master<- master %>% rename(prec_average = mpg, binomial_c = disp)
    

    You also need to include the library broom for the augment to work.

    library(broom)
    

    Define the model, and turn the results into a data frame.

    m <- glm(prec_average ~ binomial_c, family = gaussian, data = master)
    p_specprec <-  augment(m, type.predict = "response")
    
    

    Here with ggplot, we specify the data and the columns to use in the aesthetics. I guess you want to plot prec_average against its fitted values which are located at p_specprec$.fitted, also note that in the geom_line() you do not need to specify the aesthetics a second time.

    ggplot(p_specprec, aes(x = prec_average, y=.fitted)) + 
      geom_line(colour = 'blue')+
      labs(x = "Mean precipitation", y = "Species richness")