使R中的轮廓图更有效

时间:2019-05-18 20:49:32

标签: r plot

我需要一些帮助来重写我的代码。我在R中写了一些想要的轮廓图代码。该代码有效,但是它效率很低,因为它必须绘制成千上万个点才能准确得到我想要的(灰色区域),所以我想看看是否有一种更简单的方法来处理我的代码在做。

我基本上想绘制函数

f = x1 + x2

服从以下约束函数

c1 = 3/2-x1-2x2-1/2 * sin(2 * pi(x1 ^ 2-2x2))<0

c2 = x1 ^ 2 + x2 ^ 2-3 / 2 <0

因此,在c1和c2都大于零的情况下,我想将这些区域涂成灰色,只显示c1和c2小于0的函数f。x1和x2的域在0和之间。 1.

这是我当前的R代码:

x1 = seq(0,1,.001) 
x2 = seq(0,1,.001)

f = function(x1,x2){   
ans = x1 + x2   
return(ans) }


h = function(x1,x2){   
ans1 = 1.5-x1-2*x2-.5*sin(2*pi*(x1^2-2*x2))   
ans2 = x1^2+x2^2-1.5   
ans1 = sapply(ans1,function(x){max(x,0)})   
ans2 = sapply(ans2,function(x){max(x,0)})   
ans = ans1 + ans2   
return(ans) }

z = outer(x1,x2,f) 
w = outer(x1,x2,h)

image(x1,x2,z,xlab=expression(x[1]),ylab=expression(x[2])) 
contour(x1,x2,z,add=TRUE)

X = cbind(expand.grid(x1,x2),c(w)) 
points(X[X[,3]!=0,1],X[X[,3]!=0,2],pch=19,col="lightgrey")

1 个答案:

答案 0 :(得分:0)

您可以使用.filled.contour后面的工作功能filled.contour来完成此操作。 (完整的filled.contour使得注释您的绘图变得很困难。)例如

x1 = seq(0,1,.001) 
x2 = seq(0,1,.001)

f = function(x1,x2){   
  ans = x1 + x2   
  return(ans) }


h = function(x1,x2){   
  ans1 = 1.5-x1-2*x2-.5*sin(2*pi*(x1^2-2*x2))   
  ans2 = x1^2+x2^2-1.5   
  ans1 = pmax(ans1,0)   
  ans2 = pmax(ans2,0)  
  ans = ans1 + ans2   
  return(ans) }

z = outer(x1,x2,f) 
w = outer(x1,x2,h)

# Set up the plot, .filled.contour doesn't do that
plot(x1, x2, type="n", xlab=expression(x[1]),ylab=expression(x[2]))

# Set a gray background
rect(min(x1), min(x2), max(x1), max(x2), col = "gray")

# Make parts transparent
z[ w != 0 ] <- NA

# Choose the contour levels
levels <- pretty(z)

# Plot them
.filled.contour(x1,x2,z,levels, 
               hcl.colors(length(levels)-1, "ylOrRd", rev = TRUE)) 

# If your device does antialiasing, plot the filled contours twice to avoid 
# ugly effects

.filled.contour(x1,x2,z,levels, 
               hcl.colors(length(levels)-1, "ylOrRd", rev = TRUE)) 

contour(x1,x2,z, levels = levels, add=TRUE)

这给了我

screenshot