1

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!

4
  • 1
    1) You have my_func and the error says 'myfunc'. Correct this and see if it works. 2) What is the space (a, b, c) for your plots? And how do you want to plot a 3d space in 2d? With facte_wrap or facet_grid on one of the variables? Commented Dec 6, 2019 at 7:27
  • 1
    Ideally, we'd need a reproducible example of your code (example data, etc). This helps us help you ! Commented Dec 6, 2019 at 9:13
  • @RuiBarradas I fixed (1). (2) is that it should just be a curve, no? 2D. @ RoB I figure I'm making the most basic plot for a proof of concept. I should just be able to draw a math equation on ggplot, no? Commented Dec 6, 2019 at 14:44
  • With df1 <- data.frame(a = seq(0, 10, by = 0.1)) this plots a straight line: ggplot(df1, aes(x = a)) + stat_function(fun = my_func, args = list(b = 1, c = -2)). Can you post sample values for a, b and c? Commented Dec 6, 2019 at 16:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.