Juanchi
Juanchi

Reputation: 1166

Draw function in ggplot - list of parameters

Simple example of a function drawing:

p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))
p + stat_function(fun = function(x) x^2 + 1*2)

enter image description here

Is it possible to add a list of parameters inside the plot code in ggplot? Something like this?

fun1 <- function(x) x^2 + a*b
p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))
p + stat_function(fun = fun1, par=list(a=1, b=2)) + xlim(-5,5)

Upvotes: 1

Views: 777

Answers (1)

Sandipan Dey
Sandipan Dey

Reputation: 23129

Like this?

fun1 <- function(x,a,b) a*x^2 + b
p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))
p + 
  stat_function(fun = fun1, args=list(a=1, b=2)) + 
  stat_function(fun = fun1, args=list(a=2, b=1), col='red') + 
  xlim(-5,5)

enter image description here

Upvotes: 5

Related Questions