ggplot2 scale_x_log10() destroys/doesn't apply for function plotted via stat_function()

前端 未结 2 1416

I finally managed to plot my custom fitted function over my data in ggplot2 but when I log-transform the x axis the plotted function gets totally messed up. It looks like th

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-06 21:23

    Proposed Solution

    The following code is one way to get ggplot2 to do what I think you are trying to accomplish.

    library(ggplot2)
    
    # Define function. Fitted parameters included as default values.
    HillFunction = function(x, ec50=0.01, hill=0.7, rmax=1.0) {
        result = rmax / (1 + (ec50 / x)^hill)
        return(result)
    } 
    
    # Create x such that points are evenly spread in log space.
    x = 10^seq(-5, 5, 0.2) 
    y_fit = HillFunction(x)
    y_raw = y_fit + rnorm(length(y_fit), sd=0.05)
    
    dat = data.frame(x, y_fit, y_raw)
    
    plot_1 = ggplot(data=dat, aes(x=x, y=y_raw)) +
             geom_point() +
             geom_line(data=dat, aes(x=x, y=y_fit), colour="red") +
             scale_x_log10() +
             opts(title="Figure 1. Proposed workaround.")
    
    png("plot_1.png", height=450, width=450)
    print(plot_1)
    dev.off()
    

    Figure 1

    Problems With stat_function()

    1. stat_function() is trying to evaluate HillFunction() for negative values of x. This why you get the missing values error.

    2. stat_function() is not evaluating HillFunction() for any x values between 0 and 1. It is selecting x in linear space, ignoring that scale_x_log10() has been specified.

    The following code illustrates the problem, but I still can't explain why stat_function() diverges so much from y_fit in Figure 2.

    plot_2 = ggplot(dat, aes(x=x, y=y_fit)) +
             geom_point() +
             stat_function(fun=HillFunction, colour="red") +
             scale_x_log10() +
             opts(title="Figure 2. stat_function() misbehaving?")
    
    png("plot_2.png", height=450, width=450)
    print(plot_2)
    dev.off()
    
    
    png("plot_3.png", height=450, width=450)
    
    plot(x, y_fit, pch=20, log="x")
    curve(HillFunction, col="red", add=TRUE)
    title("Figure 3. curve() behaving as expected.")
    
    dev.off()
    

    Figure 2

    enter image description here

提交回复
热议问题