R在一个图中绘制具有不同参数的多个函数

时间:2016-08-17 16:06:26

标签: r ggplot2

这是Draw min, max function in R

的后续帖子

我想在一个图中绘制具有不同参数的多个函数。但ggplot的群体论证似乎不起作用。

数据:

my <- c(2012,2013, 2014)
eqs = function(x,my){
  1/(pmin(pmax(as.numeric(feTargetPv[which(feTargetPv$ModelYear == my),"c"]) * x +
                 as.numeric(feTargetPv[which(feTargetPv$ModelYear == my),"d"]),
               1/as.numeric(feTargetPv[which(feTargetPv$ModelYear == my),"a"])),
          1/as.numeric(feTargetPv[which(feTargetPv$ModelYear == my),"b"])))
}

功能:

ggplot(data.frame(x=seq(from = 30, to = 75, by = 1)), aes(x), group = my, col = my) +
  stat_function(fun=eqs, args=my) + xlab("x") + ylab("y")

Ggplot:

Warning message:
Computation failed in `stat_function()`:
unused arguments (2013, 2014)

错误消息

select *
from serverTable
where server like ‘proc1@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘proc2@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘proc3@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘pro4@server1’
order by reg_date desc
limit 1
union
select *
from serverTable
where server like ‘proc5@server1’
order by reg_date desc
limit 1

如何将我的参数提供给stat_function()?

1 个答案:

答案 0 :(得分:1)

您可以通过stat_function之外的函数计算每年的值,而不是使用ggplot,然后使用geom_line

您可以首先使用my作为ModelYear变量制作每年x值的数据集。

dat = expand.grid(x=seq(from = 30, to = 75, by = 1), ModelYear = my)

然后将x值与包含函数参数值的数据集合并。默认情况下,这仅保留第一个数据集dat的信息。

dat2 = merge(dat, feTargetPv, by = "ModelYear")

现在你的函数可以采用x,a,b,c,d或数据集和x变量的向量。

eqs = function(data, x){
    1/(pmin(pmax(as.numeric(data[,"c"]) * x +
                as.numeric(data[,"d"]),
               1/as.numeric(data[,"a"])),
           1/as.numeric(data[,"b"])))
}

将函数中的值作为列添加到数据集中。我将此新变量称为y

dat2$y = eqs(dat2, dat2$x)

现在绘图很简单,使用y值来映射y位置以及geom_line

ggplot(dat2, aes(x, y, color = factor(ModelYear))) +
    geom_line()

enter image description here