这可能很简单,但经过几个小时的搜索,我无法找到如何使用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)
)
答案 0 :(得分:6)
可以使用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)
编辑感谢@Marc_in_the_box:颜色栏的范围由zfacet
定义,而不是由z
定义
答案 1 :(得分:4)
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()
顺便说一下,我意识到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)