gpt4 book ai didi

r - 创建根据 Z 轴着色的 3D 图

转载 作者:行者123 更新时间:2023-12-02 01:16:49 26 4
gpt4 key购买 nike

 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 上的示例后放置了我的新代码。我想更改颜色,但我对新情节的可读性不是很满意

最佳答案

我稍微修改了你的代码。

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)看看 reds 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

你说你“对情节的可读性不是很满意”,但这不是很具体......我会花一段时间看 ?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

关于r - 创建根据 Z 轴着色的 3D 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10357002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com