【问题标题】:graph a function restricted in R绘制限制在 R 中的函数
【发布时间】:2014-12-01 23:17:21
【问题描述】:

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

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

【问题讨论】:

  • 您可以改用透明色。例如,如果您使用 col=rgb(1,0,0,0.5) 而不是 col="red",您将获得 50% 透明的红色而不是纯红色。
  • 此外,如果您知道给定颜色的十六进制值(请参阅here for example),您也可以使其透明。例如,"royalblue" 具有十六进制值 "#4169E1"。您可以在完全透明的00 和完全不透明的FF(255 in base 10)之间添加一个两位十六进制数,以获得所需的透明度。在您的情况下,您可以将 "royalblue" 替换为 "#4169E180" 以获得 50% 的透明度(base 16 中的 80 = base 10 中的 128)。
  • @eipi10 -- 你也可以使用adjustcolor("royalblue", alpha.f=0.5)
  • 啊,很高兴知道。谢谢乔希。

标签: r graphics plot


【解决方案1】:

一些过度绘图可能会有所帮助。上面 cmets 中建议的第一个图。然后通过分配 NA 取消选择违反约束的段,即不绘制和使用较重的颜色进行重叠绘制。 (我发现除非我冻结了它们在最后一步“移动”的 z 限制。您可能需要抑制 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()

【讨论】:

    猜你喜欢
    • 2016-07-31
    • 2012-05-14
    • 2011-01-12
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多