我终于设法将我的自定义拟合函数绘制在ggplot2中的数据上,但是当我对x轴进行对数转换时,绘制的函数完全搞砸了.它看起来scale_x_log10()
只适用于绘制的数据,但不适用于函数.
如何使功能以正确的比例显示?
以下是Hadley的stat_function()文档的修改示例:
x <- rnorm(100)
qplot(x, geom="density") + stat_function(fun = dnorm, colour="red")
Run Code Online (Sandbox Code Playgroud)
现在使用log10 x轴:
qplot(x, geom="density") + stat_function(fun = dnorm, colour="red") + scale_x_log10()
Run Code Online (Sandbox Code Playgroud)
好吧,我认为我的例子不是很有用所以我尝试的方式不同:
基本上我想要的是重现我用曲线()做的情节.我在我的数据中安装了Hill函数,现在想要绘制它:
# 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")
Run Code Online (Sandbox Code Playgroud)
所以curve()给我一个平滑的S形曲线,如预期的那样.现在我尝试用ggplot重现相同的情节:
我添加一些数据从10 ^ -5到10 ^ 5只是为了定义绘图范围,不确定是否有更好的方法
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")
Run Code Online (Sandbox Code Playgroud)
现在,如果我绘制p
一切看起来很好,就像curve()
没有logscale 的情节:
p
curve(HillFunction(ec50=hill.args$ec50,rmax=hill.args$rmax, hill=hill.args$hill,x),from=10^-5, to=10^5)
Run Code Online (Sandbox Code Playgroud)
如果我变换坐标系,我得到一个S形曲线,但根本不光滑,曲线看起来很陡,但可能来自x缩放:
p + coord_trans(x ="log10")
如果我将x刻度定义为对数刻度,则绘图看起来很平滑但在10 ^ 0处停止:
p + scale_x_log10()
Run Code Online (Sandbox Code Playgroud)
我收到以下警告: Removed 1500 rows containing missing values (geom_path).
以下代码是让ggplot2完成我认为你想要完成的事情的一种方法.
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()
Run Code Online (Sandbox Code Playgroud)
stat_function()
正试图评估HillFunction()
负值x
.这就是你得到missing values
错误的原因.
stat_function()不评估
0和1之间的HillFunction()
任何x
值.它x
在线性空间中选择,忽略scale_x_log10()
已指定的值.
下面的代码说明了这个问题,但是我仍然无法解释为什么在图2中stat_function()
偏离了这么多y_fit
.
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()
Run Code Online (Sandbox Code Playgroud)