图表限制在R中的函数

时间:2014-12-01 23:17:22

标签: r graphics plot

我想绘制一个函数:f(x,y)= x ^ 2-2 * y,带约束:x + y = 1 在我的图形函数重叠,没有看到受限函数f(x,y)。如果x + y-1 = 0是透明的,那将会更好。 R代码中的Mi代码:

x <- seq(-5, 5, length= 10)
y <- x
fun1<-function(x,y){x^2-2*y}
m <- outer(x, y, fun1)
m[is.na(m)] <- 1
persp(x, y, m, theta = 30, phi = 30,
      expand = 0.5, col = "royalblue", ltheta = 120,
      shade = 0.75, ticktype = "detailed")
par(new=TRUE)
fun1<-function(x,y){x+y-1}
m <- outer(x, y, fun2)
m[is.na(m)] <- 1
persp(x, y, m, theta = 30, phi = 30,
      expand = 0.5, col = "red", ltheta = 120,
      shade = 0.75, ticktype = "detailed")

plot

1 个答案:

答案 0 :(得分:2)

一些过度绘图可能有所帮助。上面评论中建议的第一个图。然后通过指定NA来取消选择违反约束的段,即没有具有较重颜色的绘图和上绘图。 (我发现除非我冻结了z限制,否则他们会在最后一步移动#34;你可能需要抑制z轴标签,因为它们仍然相互叠加。)

 png(); x <- seq(-5, 5, length= 10)
y <- x
fun1<-function(x,y){x^2-2*y}
m1 <- outer(x, y, fun1)
m1[is.na(m)] <- 1
persp(x, y, m1, theta = 30, phi = 30,
      expand = 0.5, col = "#4169E155", ltheta = 120,
      shade = 0.75, ticktype = "detailed",zlim=c(-15,35))
par(new=TRUE)

fun2<-function(x,y){x+y-1}
m2 <- outer(x, y, fun2)
m2[is.na(m)] <- 1
persp(x, y, m2, theta = 30, phi = 30,
      expand = 0.5, col = adjustcolor("red", alpha.f=0.5), ltheta = 120,
      shade = 0.75, ticktype = "detailed",zlim=c(-15,35))
par(new=TRUE)

fun3<-function(x,y){x^2-2*y}
m3 <- outer(x, y, fun3)
m3[ m3 < m2 ] <- NA   #     <--- logical indexing; this is the key step
persp(x, y, m3, theta = 30, phi = 30,
      expand = 0.5, col = "#4169E1", ltheta = 120,  # solid-blue
      shade = 0.75, ticktype = "detailed",zlim=c(-15,35));dev.off()

enter image description here