简体   繁体   中英

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!

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)))

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM