如何在R中使用两个变量绘制函数图 [英] How to graph function with two variables in R

查看:121
本文介绍了如何在R中使用两个变量绘制函数图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我花了最后四个小时试图找到一种有效的方法来绘制具有两个变量的函数的曲线-无济于事.我实际上可以付诸实践的唯一答案不是产生我所期望的多线图.

我创建了一个带有两个变量x和y的函数,它返回一个连续的数值.我想在单个屏幕上绘制此函数的结果,其中包含x的某些值以及给定范围内y的所有可能值(y也是连续变量).

类似的东西:

这两个问题确实有所帮助,但我仍然无法到达那里:

So, I've spent the last four hours trying to find an efficient way of plotting the curve(s) of a function with two variables - to no avail. The only answer that I could actually put to practice wasn't producing a multiple-line graph as I expected.

I created a function with two variables, x and y, and it returns a continuous numeric value. I wanted to plot in a single screen the result of this function with certain values of x and all possible values of y within a given range (y is also a continuous variable).

Something like that:

These two questions did help a little, but I still can't get there:

Plotting a function curve in R with 2 or more variables

How to plot function of multiple variables in R by initializing all variables but one

I also used the mosaic package and plotFun function, but the results were rather unappealing and not very readable: https://www.youtube.com/watch?v=Y-s7EEsOg1E.

Maybe the problem is my lack of proficiency with R - though I've been using it for months so I'm not such a noob. Please enlighten me.

解决方案

Say we have a simple function with two arguments:

fun <- function(x, y) 0.5*x - 0.01*x^2 + sqrt(abs(y)/2)

And we want to evaluate it on the following x and y values:

xs <- seq(-100, 100, by=1)
ys <- c(0, 100, 300)

This line below might be a bit hard to understand but it does all of the work:

res <- mapply(fun, list(xs), ys)

mapply allows us to run function with multiple variables across a range of values. Here we provide it with only one value for "x" argument (note that xs is a long vector, but since it is in a list - it's only one instance). We also provide multiple values of "y" argument. So the function will run 3 times each with the same value of x and different values of y.

Results are arranged column-wise so in the end we have 3 columns. Now we only have to plot:

cols <- c("black", "cornflowerblue", "orange")
matplot(xs, res, col=cols, type="l", lty=1, lwd=2, xlab="x", ylab="result")
legend("bottomright", legend=ys, title="value of y", lwd=2, col=cols)

Here the matplot function does all the work - it plots a line for every column in the provided matrix. Everything else is decoration.

Here is the result:

这篇关于如何在R中使用两个变量绘制函数图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆