Search code examples
rggplot2loess

Adding a loess smooth after log-transformation of x-scale


I am plotting residuals vs Time and I am adding a loess smooth curve on the plot. When I change the x-scale to a log scale, the loess smooth disappear and I can't add it after that. When I ask for displaying the graph after log-transformation of x-axis, the following error appear in RStudio:

Error in seq.default(range[1], range[2], length = n) :'from' cannot be NA, NaN or infinite. 

What am I doing wrong? how can I add a loess smooth on a log x-scale ? He is my code for the plot:

max.CWRES <- max(abs(data$CWRES),na.rm=T)
plotobj3 <- NULL
plotobj3 <-  ggplot(data[data$CONC!=0,])
plotobj3 <- plotobj3 + geom_point(aes(x=TIME, y=CWRES, colour=DOSE), shape=1, size=3)
plotobj3 <- plotobj3 + geom_abline(aes(x=TIME, y=CWRES),intercept=0, slope=0, colour="black")        

#Add loess smoothing line
plotobj3 <- plotobj3 + geom_smooth(aes(x=TIME, y=CWRES), method="loess", se=F, span=1.5,   colour="green")       
plotobj3 <- plotobj3+ scale_x_continuous(name="Time (hours)")
plotobj3 <- plotobj3+ scale_y_continuous(name="CWRES", limits=c(-max.CWRES ,max.CWRES))

# log scale for x-axis
plotobj3 <- plotobj3+ scale_x_log10(name="TIME (hours)")
plotobj3

Solution

  • The problem here appears to be that you start with TIME = 0. When you log10-transform your x axis, log-time then starts at -Inf. You should (at least for the loes part) only use the data with TIME > 0:

    plotobj3 + geom_smooth(aes(x = TIME, y=CWRES), 
                           data = data[data$TIME > 0 & data$CONC != 0, ], #this is the crucial part
                           method = "loess", 
                           se = FALSE, 
                           span = 1.5,   
                           colour = "green")        
    

    Note that this uses the original data for the model fitting. If you would like to use the log10 data for model fitting, you can use aes(x=log10(TIME), y=CWRES) everywhere instead of aes(x=TIME, y=CWRES)