user26481
user26481

Reputation: 63

How to plot custom math equation in R ggplot2

I need to pass a set of coefficients to ggplot2, and plot that equation.

stat_function() does not seem to work with anything but one variable, and I have 17.

Here's an example of a multivariate equation I would want

my_func <- function(a, b, c) {2*a -4*b + 8*c }
ggplot + stat_function(fun = my_func) 

This is the output:

Warning message: “Computation failed in `stat_function()`: argument "b" is missing, with no default”

I also tried with

+ layer(stat = "function", fun = my_func) 

No luck.

Also I might as well ask, I have various sets of these coefficients and it'd be great if I could build each "formula" automatically.

Thanks for the help!

Upvotes: 1

Views: 1911

Answers (1)

m.evans
m.evans

Reputation: 677

I'm not sure if this exactly what you have in mind, but often what people do when visualizing differences in coefficients is plotting curves in different colors or linetypes on the same plot. To do this, you'll need to create a new column of your response y and then plot that.

library(ggplot2)

df <- data.frame(expand.grid(a = 1:10,
                 b = c(1,5,10),
                 c = c(1,2,3)))
#create a column referring to which levels of coefficents b and c you are using
df$coefficients <- paste0("b = ", df$b, ", c = ", df$c)

my_func <- function(a, b, c) {2*a -4*b + 8*c }

#calculate your response as a function of your variables
df$y <- my_func(a = df$a, b = df$b, c = df$c)

ggplot(df, aes(x = a, y = y, group = coefficients)) +
  geom_line(aes(color = as.factor(b), linetype = as.factor(c)))

enter image description here

This will get rather unwieldy with 17 variables, but you could look at using facet_wrap or simply just holding other coefficients constant.

Upvotes: 1

Related Questions