繁体   English   中英

如何在 R ggplot2 中绘制自定义数学方程

[英]How to plot custom math equation in R ggplot2

我需要将一组系数传递给 ggplot2,并绘制该方程。

stat_function() 似乎只对一个变量起作用,而我有 17 个。

这是我想要的多元方程的一个例子

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

这是输出:

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

我也试过

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

没运气。

另外我不妨问一下,我有各种这些系数集,如果我可以自动构建每个“公式”,那就太好了。

谢谢您的帮助!

我不确定这是否正是您的想法,但通常人们在可视化系数差异时所做的是在同一绘图上以不同颜色或线型绘制曲线。 为此,您需要为响应y创建一个新列,然后对其进行绘制。

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

在此处输入图片说明

对于 17 个变量,这将变得相当笨拙,但您可以考虑使用facet_wrap或只是保持其他系数不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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