【问题标题】:Overlay multiple stat_function calls in ggplot2在 ggplot2 中覆盖多个 stat_function 调用
【发布时间】:2011-03-23 06:17:37
【问题描述】:

我有两个数据框rawcoef

  • 包含原始数据的文件
  • 另一个包含我从原始数据中得出的建模系数。

第一个数据框raw 包含:

  • Time(0 到 900 秒)
  • OD 用于许多变体和四次运行。

第二个数据框coef 包含:

  • 每个变体/运行组合一行,在该行中包含各个系数(MD.1t0.1)。

我已经绘制了每个 Variant 的原始数据拆分,并用 runID 着色,没有问题。但是,现在我想根据runID覆盖模型曲线。

由于建模系数在不同的数据框中,具有不同的维度,我不能只cbind他们。 stat_function 对我不起作用。我一次只能显示一条曲线。

我试过for loop,每次都添加stat_function层:

p <- ggplot(temp, aes(Time, OD)) + geom_point(aes(colour = runID), size = 2) #works fine!
calc <- function(x){temp.n$M[ID] * (1 - exp(temp.n$D.1[ID] * temp.n$t0.1[ID] - x)))}
for(ID in 1:length(unique(temp.n$runID))) {
  p <- p + stat_function(fun = calc)
}
print(p)

最后,所有p 返回的是原始数据的图,以及循环位的最终曲线。每次我尝试添加新的stat_function 层时,p 似乎都会恢复到原来的状态。

有什么想法吗?

【问题讨论】:

  • 也许最简单的解决方法是合并 data.frames。这可行吗?
  • 你能提供一个可重现的例子吗?问题在于您使用了变量范围。

标签: r function overlay plot ggplot2


【解决方案1】:

按照given here的解决方案,你可能不得不自己模仿stat_function的效果。由于您没有给出可重复的示例,因此我创建了一个简单的示例,希望能模仿您的问题:

library(ggplot2)
reg.fun <- function(x, par1, par2){exp(-x*par1) + par2} #functional form
reg <- data.frame(g=factor(1:3), par1=(1:3)/10, par2=1:3)  #parameters for 3 groups

#generate data from reg.fun
dd <- expand.grid(x=0:9, g=reg$g)         #set x values, and 3 groups from reg
dd <- merge(dd, reg)                      #"import" parameters
dd$mn <- with(dd, reg.fun(x, par1, par2)) #value of function for given x's
dd$y <- rnorm(30, mean=dd$mn, sd=0.5)     #add variability
dd <- subset(dd, select=c(g,x,y))         #remove auxiliary variables 

#similarly to above generate values for the function on a fine grid of x values
pred.dd <- expand.grid(x=seq(0,9, length=101), g=levels(dd$g))
pred.dd <- merge(pred.dd, reg)
pred.dd$y <- with(pred.dd, reg.fun(x, par1, par2))

#draw the plot
p <- qplot(x,y, colour=g, data=dd)  #scatterplot of data
p + geom_line(data=pred.dd)         #add the curves of the functions 

【讨论】:

    【解决方案2】:

    我和你有同样的问题。在一个非常不优雅的解决方案中,我发现的唯一解决方案是将 stat 函数组合在一起,如下所示:

    p <- ggplot(temp, aes(Time, OD)) + geom_point(aes(colour = runID), size = 2) #works fine!
    
    calc <- function(x){temp.n$M[ID] * (1 - exp(temp.n$D.1[ID] * temp.n$t0.1[ID] - x)))}
        p <- p +
          stat_function(fun = function(x){temp.n$M[1] * (1 - exp(temp.n$D.1[1] * temp.n$t0.1[1] - x)))) + 
          stat_function(fun = function(x){temp.n$M[2] * (1 - exp(temp.n$D.1[2] * temp.n$t0.1[2] - x)))) +
          stat_function(fun = function(x){temp.n$M[3] * (1 - exp(temp.n$D.1[3] * temp.n$t0.1[3] - x)))) +
          # etc
    

    如果您只有几行要添加,这很好,但如果您有很多行,那就不行了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多