根据Z轴创建彩色三维图

时间:2012-04-27 19:53:19

标签: r 3d plot

 library(Sleuth2)

 mlr<-lm(ex1222$Buchanan2000~ex1222$Perot96*ex1222$Gore2000)


for (i in 0:3) {
           assign(paste("betaHat", i, sep=""), 
           summary(mlr)$coeff[i+1,1])
               }

x<-sort(ex1222$Perot96)
y<-sort(ex1222$Gore2000)


z1 <- outer(x, y, function(a,b) betaHat0+betaHat1*a+betaHat2*b+betaHat3*a*b)
nrz <- nrow(z)
ncz <- ncol(z)

# Create a function interpolating colors in the range of specified colors
jet.colors <- colorRampPalette( c("blue", "red") ) 

# Generate the desired number of colors from this palette
nbcol <- 100
color <- jet.colors(nbcol)

# Compute the z-value at the facet centres
zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]

# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)

persp(x, y, z1, col=color[facetcol],theta=-30, lwd=.3,xlab="Perot 96", ylab="Gore 2000", zlab="Predicted Votes for Buchanan")

你好,

我正在尝试为上面的情节着色。我想我想要更高的'z'颜色更深的红色(或任何颜色)的值。

如何实现这一目标的任何帮助将不胜感激。

另外,请随意提出一个不同的功能来实现这一点。

谢谢!

编辑....我在查看?persp上的示例后放了我的新代码。我想改变颜色,我对新剧情的可读性并不十分满意

1 个答案:

答案 0 :(得分:5)

我稍微修改了你的代码。

library(Sleuth2)

使用data参数通常比通过$使用从数据框中提取的预测变量更好的做法:

mlr<-lm(Buchanan2000~Perot96*Gore2000,data=ex1222)

我们可以使用expand.grid()predict()以清晰的方式获得回归结果:

perot <- seq(1000,40000,by=1000)
gore <-  seq(1000,400000,by=2000)

如果您希望在观察位置评估构面,则可以改为使用perot <- sort(unique(ex1222$Perot96)); gore <- sort(unique(ex1222$Gore2000))

pframe <- with(ex1222,expand.grid(Perot96=perot,Gore2000=gore))
mlrpred <- predict(mlr,newdata=pframe)

现在将预测转换为矩阵:

nrz <- length(perot)
ncz <- length(gore)
z <- matrix(mlrpred,nrow=nrz)

我选择从浅红色(#ffcccc,红色带有相当多的蓝色/绿色)变为深红色(#cc0000,有点红色,没有别的东西)。

jet.colors <- colorRampPalette( c("#ffcccc", "#cc0000") ) 

您还可以使用grep("red",colors(),value=TRUE)查看R内置的红色。

# Generate the desired number of colors from this palette
nbcol <- 100
color <- jet.colors(nbcol)

# Compute the z-value at the facet centres
zfacet <- z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)

persp(perot, gore, z,
      col=color[facetcol],theta=-30, lwd=.3,
      xlab="Perot 96", ylab="Gore 2000", zlab="Predicted Votes for Buchanan")

enter image description here

你说你对可读性感到非常满意&#34;情节,但那不是很具体......我会花一点时间在?persp页面看看你的选择是什么......

另一个选择是rgl包:

library(rgl)
## see ?persp3d for discussion of colour handling
vertcol <- cut(z, nbcol)
persp3d(perot, gore, z,
      col=color[vertcol],smooth=FALSE,lit=FALSE,
      xlab="Perot 96", ylab="Gore 2000", zlab="Predicted Votes for Buchanan")

enter image description here

scatter3d包中查看car可能也值得一看(SO上还有其他帖子描述了如何调整其某些图形属性)。

library(car)
scatter3d(Buchanan2000~Perot96*Gore2000,data=ex1222)

enter image description here