Reputation: 71
This is a follow up post to Draw min, max function in R
I would like to draw multiple functions with different parameters in one plot. But the group argument of ggplot does not seem to work.
Data:
# data preparation/ load
feTargetPv <- structure(list(ModelYear = 2012:2016,
ComplianceCategory = c("pv","pv", "pv", "pv", "pv"),
fetargetfix = c(30.7, 31.4, 32.1, 33.3, 34.7),
a = c("35.95", "36.8", "37.75", "39.24", "41.09"),
b = c("27.95", "28.46", "29.03", "29.9", "30.96"),
c = c("0.0005308", "0.0005308", "0.0005308", "0.0005308", "0.0005308"),
d = c("0.006057", "0.00541", "0.004725", "0.003719", "0.002573")),
.Names = c("ModelYear", "ComplianceCategory", "fetargetfix", "a", "b", "c", "d"),
row.names = c(47L, 49L, 51L, 53L, 55L), class = "data.frame")
Function:
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:
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")
Error message
Warning message:
Computation failed in `stat_function()`:
unused arguments (2013, 2014)
How do I have to provide the my parameters to the stat_function()?
Upvotes: 0
Views: 1384
Reputation: 36114
Rather than using stat_function
, you could calculate the values per year via your function outside of ggplot
and then use geom_line
.
You could start by making a dataset of your x values for each year, using your my
as your ModelYear
variable.
dat = expand.grid(x=seq(from = 30, to = 75, by = 1), ModelYear = my)
Then merge your x values with the dataset that contains the function parameter values. By default this keeps only info for the first dataset, dat
.
dat2 = merge(dat, feTargetPv, by = "ModelYear")
Now your function can take either the vectors of x, a, b, c, d or the dataset and the x variable.
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"])))
}
Add the values from the function as a column to the dataset. I call this new variable y
.
dat2$y = eqs(dat2, dat2$x)
Now the plotting is straightforward, using y values to map the y position along with geom_line
.
ggplot(dat2, aes(x, y, color = factor(ModelYear))) +
geom_line()
Upvotes: 1