color.legend: Adds Color Legend to Plot Margin

View source: R/color.legend.R

color.legendR Documentation

Adds Color Legend to Plot Margin

Description

This function can be used to add a color legend to the margin of a plot produced by image.

Usage

color.legend(zlim, side = 4, col = NULL, ncol = NULL, zlab = "z", 
             zline = 2.5, box = TRUE, zcex = 1, ...)

Arguments

zlim

numeric vector of the form c(min, max) giving the range of values for the color legend.

side

which side (margin) should the legend be added to? 1 = bottom, 2 = left, 3 = top, 4 = right (default).

col

colors to use for the legend. Can input the name of a color palette (see hcl.colors) or a vector of colors to create a palette (see colorRampPalette).

ncol

number of colors to use for the legend. Defaults to length(col).

zlab

axis label for the color legend.

zline

line number to draw axis label.

box

add a box around the legend?

zcex

scale factor for axis label.

...

additional arguments passed to image function.

Details

The colorRampPalette function is used to create a vector of colors of length ncol that span the colors included in col. Then the image function is used to draw a color legend with values spanning zlim.

Value

Produces a color legend.

Note

You will likely need to use par()$plt or par()$fig to make enough room in the appropriate margin (see example).

Author(s)

Nathaniel E. Helwig <helwig@umn.edu>

References

Helwig, N. E. (2020). Multiple and Generalized Nonparametric Regression. In P. Atkinson, S. Delamont, A. Cernat, J. W. Sakshaug, & R. A. Williams (Eds.), SAGE Research Methods Foundations. https://doi.org/10.4135/9781526421036885885

See Also

plot.gsm for effect plots from gsm objects

plot.sm for effect plots from sm objects

Examples

# define function
fun <- function(x){
  exp(-rowSums(x^2)/2)
}

# define xgrid
nx <- 101
x <- y <- seq(-3, 3, length.out = nx)
xy <- expand.grid(x1 = x, x2 = y)

# evaluate function
z <- matrix(fun(xy), nx, nx)

# define colors
colors <- c("#053061", "#2166ac", "#4393c3", "#92c5de", "#d1e5f0", "#f7f7f7",
            "#fddbc7", "#f4a582", "#d6604d", "#b2182b", "#67001f")
col <- colorRampPalette(colors)(21)

# setup par
oplt <- par()$plt
par(plt = c(0.15, 0.8, oplt[3:4]))

# plot image
image(x, y, z, col = col)

# add legend
par(plt = c(0.85, 0.9, oplt[3:4]), new = TRUE)
color.legend(range(z), col = col, ncol = length(col))

# restore original par()$plt
par(plt = oplt)

npreg documentation built on May 29, 2024, 4:17 a.m.

Related to color.legend in npreg...