可能这样做很简单,但经过几个小时的搜索,我无法找到如何使用R在persp图旁边添加colorbar.有人可以帮忙吗?谢谢.
persp(w_lb, w_dti, cm[[i]],
theta = -30, phi = 30, expand = 0.95,
col=color[facetcol], shade = 0.25,
ticktype = "detailed", border = NA,
xlab = "LB", ylab = "DT", zlab="CM",
zlim=c(0.0, 1.0)
)
Run Code Online (Sandbox Code Playgroud)
可以image.plot在fields包中添加图例.使用以下示例?persp:
library(fields)
## persp example code
par(bg = "white")
x <- seq(-1.95, 1.95, length = 30)
y <- seq(-1.95, 1.95, length = 35)
z <- outer(x, y, function(a, b) a*b^2)
nrz <- nrow(z)
ncz <- ncol(z)
# Create a function interpolating colors in the range of specified colors
jet.colors <- colorRampPalette( c("blue", "green") )
# 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])/4
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)
persp(x, y, z, col = color[facetcol], phi = 30, theta = -30, axes=T, ticktype='detailed')
## add color bar
image.plot(legend.only=T, zlim=range(zfacet), col=color)
Run Code Online (Sandbox Code Playgroud)
编辑感谢@Marc_in_the_box:颜色栏的范围由zfacet,而不是由.定义z

persp有一种基于面的中点计算颜色的棘手方法。这使得你的工作在提取颜色级别时有点困难,但我想我已经找到了一种方法。无论如何,layout这可能是拆分设备并添加颜色条的最佳选择:
layout(matrix(1:2, nrow=1, ncol=2), widths=c(4,1), heights=1)
par(bg = "white", mar=c(4,4,1,1))
x <- seq(-1.95, 1.95, length = 30)
y <- seq(-1.95, 1.95, length = 35)
z <- outer(x, y, function(a, b) a*b^2)
nrz <- nrow(z)
ncz <- ncol(z)
# Create a function interpolating colors in the range of specified colors
jet.colors <- colorRampPalette( c("blue", "green") )
# 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])/4
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)
persp(x, y, z, col = color[facetcol], phi = 30, theta = -30)
labs <- levels(facetcol)
tmp <- cbind(lower = as.numeric( sub("\\((.+),.*", "\\1", labs) ),
upper = as.numeric( sub("[^,]*,([^]]*)\\]", "\\1", labs) ))
par(mar=c(10,0,10,5))
image(x=1, y=rowMeans(tmp), matrix(rowMeans(tmp), nrow=1, ncol=nbcol), col=color, axes=FALSE, xlab="", ylab="")
axis(4)
box()
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我意识到最后一个例子看起来persp在计算面值时有一个错误 - 事实上,它们是角值的总和,需要除以 4 才能直接使用它们来提取颜色断点:
# 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)
#should be:
# Compute the z-value at the facet centres
zfacet <- (z[-1, -1] + z[-1, -ncz] + z[-nrz, -1] + z[-nrz, -ncz]) / 4
# Recode facet z-values into color indices
facetcol <- cut(zfacet, nbcol)
Run Code Online (Sandbox Code Playgroud)