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
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()
stat_function()
is trying to evaluate HillFunction()
for
negative values of x
. This why you get the missing values
error.
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()