How to add colorbar with perspective plot in R

后端 未结 2 1766
闹比i
闹比i 2021-01-03 07:04

May be it is very simple to do, but after hours of searching I didn\'t able to find how to add colorbar beside the persp plot using R. Could anyone kindly help? Thanks.

2条回答
  •  Happy的楠姐
    2021-01-03 07:38

    It's possible to add a legend using image.plot in the fields package. 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 range of the colorbar is defined by zfacet, not by z persp with colorbar

提交回复
热议问题