Angelina
Angelina

Reputation: 71

geom_function with user written function in ggplot

I will be highly grateful for your help. I am learning how to use geom_function in r. Following is my function:

x0 <- 0.5
x1 <- 1
x2 <- 2
x3 <- 3

x <- c(x0, x1, x2, x3)

myfn <- function(w, b, a, x){
    w^(1-b)/(1-b)-a*w-(w>100 & w<=200)*x[3]*(w-100)-(w>200)*x[3]*100-x[4]*(w-200)
}

My objective is to plot above function using geom_function to see how this function behaves with different values of arguments a and b and following is my code:

y=seq(0,1000,5)

ggplot()+
  xlim(c(0,1000))+
  geom_function(fun=myfn(w=y, b=-4, a=0.5, x=x))

Problem: I feel my logic is correct but when I execute above code, I get nothing. I will be highly grateful for the help. Thank you very much for the help in advance. Any help or direction will be highly appreciated.

Upvotes: 2

Views: 2330

Answers (2)

stefan
stefan

Reputation: 125687

Your function myfn is a function of w where a, b and x are parameters. To plot this function over the range of c(0, 1000) pass your function to the fun argument and the parameters as a list via the args argument and set the range via xlim:

x0 <- 0.5
x1 <- 1
x2 <- 2
x3 <- 3

x <- c(x0, x1, x2, x3)

myfn <- function(w, b, a, x) {
  w^(1 - b) / (1 - b) - a * w - (w > 100 & w <= 200) * x[3] * (w - 100) - (w > 200) * x[3] * 100 - x[4] * (w - 200)
}

library(ggplot2)

ggplot() +
  xlim(c(0, 1000)) +
  geom_function(fun = myfn, args = list(b = -4, a = 0.5, x = x))

A second option would be to make use of a lambda function like so:

ggplot() +
  xlim(c(0, 1000)) +
  geom_function(fun = ~ myfn(.x, b = -4, a = 0.5, x = x))

Upvotes: 3

Merijn van Tilborg
Merijn van Tilborg

Reputation: 5897

myfn <- function(x, a, b, c) {
  x^(1 - b) / (1 - b) - a * x - (x > 100 & x <= 200) * c[3] * (x - 100) - (x > 200) * c[3] * 100 - c[4] * (x - 200) # outcome is y
}

ggplot() +
  xlim(c(0, 1000)) +
  geom_function(fun = ~ myfn(x = .x, a = 0.5, b = -4, c = c(0.5, 1, 2, 3)))

If you do not want to add the variables through the args list you can add the variables to your function like this. Note I changed some of the variable names to make it more clear what the actual x and y are in the plot. Also x by the OP is just a list with 4 constants, I provided them as a and b under the name c.

Upvotes: 2

Related Questions