color_bar: Color legend

View source: R/plot_extra.R

color_barR Documentation

Color legend

Description

Continuous color bar legend.

Usage

color_bar(
  colors,
  x = NULL,
  y = x,
  labels = NULL,
  at.x = par("usr")[2L],
  at.y = par("usr")[3L],
  cex.x = 1,
  cex.y = 1,
  ...
)

Arguments

colors

vector of color names (or hexadecimal) from low to high

x

numeric vector of data

y

optional numeric vector of data; to color by a variable other than x, y must be specified for labels coordinates to work properly; see examples

labels

optional labels for color bar

at.x

x-coordinate of lower-left corner of bar

at.y

y-coordinate of lower-left corner of bar; note that the bar can extend ouside the plotting region, so use cex.x and cex.y to scale the bar down (or up)

cex.x, cex.y

scaling parameters

...

additional graphical parameters passed to par

Value

An invisible vector of colors (hexadecimal format) used for the bar. Note that these colors may be mapped to x so that only one color_bar needs to be called in the col argument for both the coloring of points and the generation of the legend; see examples.

Examples

plot.new()
color_bar(c('black','red','white','blue'), at.x = 0, at.y = 0)
text(x = 0, y = seq(0, par('usr')[4], length.out = 6), pos = 4, xpd = TRUE,
     labels = pretty(seq(0, par('usr')[4]), n = 6), cex = 0.8, offset = 0.75)


## calling color_bar once in the col argument will color x accordingly
## and plot the legend simultaneously

## compare
plot(mtcars$mpg, pch = 19, cex = 2, 
     col = rawr:::col_scaler(mtcars$mpg, c('yellow', 'red')))
plot(mtcars$mpg, pch = 19, cex = 2,
     col = color_bar(c('yellow', 'red'), mtcars$mpg, labels = mtcars$mpg))


## plot a color_bar legend by a variable other than x
##   use y argument to match the variable in the original plot call
##   and x as the variable to color and label

## compare
with(mtcars, {
  plot(mpg, pch = 19, cex = 2,
       main = 'color by weight (red = heavier)',
       col = rawr:::col_scaler(wt, c('yellow', 'red')))
})

with(mtcars, {
  plot(mpg, pch = 19, cex = 2,
       main = 'color by weight (red = heavier)',
       col = color_bar(c('yellow', 'red'), x = wt, y = mpg, labels = wt))
})


raredd/plotr documentation built on Nov. 19, 2023, 4:09 a.m.