user330
user330

Reputation: 1290

How to wrap ggplot2 as a function in R

I want to wrap the following codes as a function

ez <- function(x,a) { 
    z<-x^3+1
    return(z)
} 
Q1 <- c(1,2,3,4,5)
ggplot(tibble(x = c(-10, 10)), aes(x)) +
    map(1:length(Q1), 
        ~stat_function(fun = ez, aes(color = paste0("sand ", .)), args=list(a = Q1[.])))

These codes develop multiple curves, but they are OVERLAP and it does not matter.

I want to generate a function like this

   plot <- function(a) {
Q1 <- c(1,2,3,4,5)
 ggplot(tibble(x = c(-6, 6)), aes(x)) +
      map(1:length(Q1), 
          ~stat_function(fun = ez, aes(color = paste0("sand ", .)), args=list(a = Q1[.])))

}
plot(2, 4, 3,6)

Upvotes: 0

Views: 117

Answers (1)

stefan
stefan

Reputation: 125807

Maybe this is what your are looking for. As far as I get it you want to make a function, which you can pass a vector of parameters and which returns a plot of curves for the chosen parameters. To this end:

  1. Pass the parameter values as a vector, i.e. put it in c(...)
  2. In your plot function simply loop over a

Note: I adjusted the function ez to give different values (and non-overlapping curves) depending on a

ez <- function(x,a) { 
  z<-x^3+a^3
  return(z)
}

library(ggplot2)
library(tibble)
library(purrr)

plot <- function(a) {
  ggplot(tibble(x = c(-6, 6)), aes(x)) +
    map(a, 
        ~stat_function(fun = ez, aes(color = paste0("sand ", .)), args=list(a = .)))
  
}
plot(c(2, 4, 3, 6))

Upvotes: 3

Related Questions