R:绘制二维函数?

时间:2016-09-18 15:14:27

标签: r

假设我有一个函数x ^ 2 + y ^ 2 = 1,我怎样才能在R中绘制这个函数?

我试过了: enter image description here

但它不起作用并说: enter image description here

2 个答案:

答案 0 :(得分:2)

绘制圆圈:

plot.new()
plot.window(xlim = c(-1, 1), ylim = c(-1, 1)) 
theta <- seq(0, 2 * pi, length = 200) 
lines(x = cos(theta), y = sin(theta))

enter image description here

使用原点和纵横比= 1

绘制单位圆
plot(0, 0, asp = 1, xlim = c(-1, 1), ylim = c(-1, 1))
lines(x = cos(theta), y = sin(theta), col = "red")

enter image description here

绘制表面

我们将使用不同的功能。

f <- function(x, y) {
  cos(x) + sin(y)
}

xvec <- yvec <- seq(-pi, pi, length = 100)
dat <- expand.grid(x = xvec, y = yvec)
zmat <- matrix(f(dat$x, dat$y), ncol = 100)

# use persp
persp(xvec, yvec, zmat)

enter image description here

# view from a different angle
persp(xvec, yvec, zmat, theta = 45)

enter image description here

使用ggplot2

library(ggplot2)
dat$z <- f(dat$x, dat$y)

ggplot(dat) + 
  aes(x = x, y = y, fill = z) + 
  geom_tile() + 
  scale_fill_gradient2()

enter image description here

答案 1 :(得分:0)

试试这个:

x <- seq(-1,1,.01)
plot(0,0, xlim=c(-1,1), ylim=c(-1,1))
curve(sqrt(1-x^2), add=TRUE)
curve(-sqrt(1-x^2), add=TRUE)