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 the scale_x_log10()
applies only to the plotted data but not to the function.
How can I make the function to appear in the correct scale?
Here is an modified example from Hadley's stat_function() documentation:
x <- rnorm(100)
qplot(x, geom="density") + stat_function(fun = dnorm, colour="red")
and now with log10 x-axis:
qplot(x, geom="density") + stat_function(fun = dnorm, colour="red") + scale_x_log10()
update
Okay, I think my example was not very helpful so I try it differently:
essentially what I want is to reproduce a plot I did with curve(). I fitted a Hill function to my data and now want to plot it:
# the function
HillFunction <- function(ec50,hill,rmax,x) {rmax/(1+(ec50/x)^hill)}
# fitted parameters
hill.args <- list(ec50=10^-2, hill=.7, rmax=1)
curve(HillFunction(ec50=hill.args$ec50,rmax=hill.args$rmax, hill=hill.args$hill,x),from=10^-5, to=10^5,log="x")
so curve() gives me a smooth sigmoidal curve as expected. Now I try to reproduce the same plot with ggplot:
I add some data from 10^-5 to 10^5 just to define the plotting range, not sure if there are better ways
p <- ggplot(data=data.frame(x=c(10^-5:10^5)), aes(x=x)) + stat_function(fun=HillFunction, args=hill.args, n=3000, color="red")
now if I plot p
everything looks fine, like the curve()
plot without the logscale:
p
curve(HillFunction(ec50=hill.args$ec50,rmax=hill.args$rmax, hill=hill.args$hill,x),from=10^-5, to=10^5)
If I transform the coordinate system I get a sigmoidal curve but not smooth at all and the curve looks way to steep, but maybe that comes from x-scaling:
p + coord_trans(x="log10")
And if I define the x scale to be a log-scale the plot looks smooth but stops at 10^0:
p + scale_x_log10()
and I get the following warning: Removed 1500 rows containing missing values (geom_path).
See Question&Answers more detail:
os