0

I realize similar questions have already been asked already. For example, consider the one here: Equivalent of curve() for ggplot. Is it possible to plot the functions below using group somehow or would I have to write stat_function for each instance of a and b?

myfun <- function(x, i) {
  sin(a[i] * x) + log(b[i] * x)
}

ggplot(data.frame(x=c(0, 10)), aes(x)) + 
  stat_function(fun = myfun(x, 1)) +
  stat_function(fun = myfun(x, 2)) ...

What if a and b are big? The above seems inelegant.

Community
  • 1
  • 1
johnson-shuffle
  • 1,023
  • 5
  • 11

1 Answers1

4

I would not use stat_function for anything non-trivial, it's usually easier to explicitly create values,

myfun <- function(a, b, x) {
  data.frame(x = x, y = sin(a * x) + log(b * x))
}

ab <- expand.grid(a=1:3, b=2:6)
d <- plyr::mdply(ab, myfun, x=seq(0,10, length=100))

ggplot(d, aes(x, y, colour=factor(a))) + 
  facet_wrap(~b) +
  geom_line()

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294