How to add a color panel with a perspective in R

It may be very simple to do, but after several hours of searching, I could not find how to add a colorbar next to the persp plot using R. Can anyone kindly help? Thank.

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)
)
+4
source share
2 answers

You can add a legend using image.plotthe package fields. Using an example from ?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)

EDIT thanks to @Marc_in_the_box: the color bar range is determined zfacet, notz persp with colorbar

+6
source

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

enter image description here

btw, , 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)
+4

Source: https://habr.com/ru/post/1533474/


All Articles