Skip to content

Instantly share code, notes, and snippets.

@bjurban
Last active August 29, 2015 14:18
Show Gist options
  • Save bjurban/a3548427496baad22381 to your computer and use it in GitHub Desktop.
Save bjurban/a3548427496baad22381 to your computer and use it in GitHub Desktop.
# adding a custom legend to levelplot when z values are categorical (not continuous)
library(lattice)
foo <- expand.grid(x = 1:10, y=1:10)
foo$z <- as.integer(runif(100)*3)
# foo$z takes on values of 0, 1 or 2: this could represent a factor
# default levelplot
levelplot(z~x*y, foo)
# levelplot with custom colors and custom legend
my.colors <- c("blue", "green", "red")
my.labels <- c("category 1", "category 2", "category 3")
levelplot(z~x*y, foo,
col.regions = my.colors,
cuts = 2,
colorkey=FALSE,
key=list(space="top", columns=3,
rect=list(col=my.colors, border="transparent", size=1),
text=list(lab=my.labels),
cex=0.6,
between.columns=3,
between=1)
)
# levelplot with custom colors and custom legend on right side
levelplot(z~x*y, foo,
col.regions = my.colors,
cuts = 2,
colorkey=FALSE,
key=list(space="right", columns=1,
rect=list(col=my.colors, border="transparent", size=2, height=0.6),
text=list(lab=my.labels),
cex=0.6,
between.columns=3,
between=1,
padding.text=4)
)
# see also:
# http://www.magesblog.com/2012/12/changing-colours-and-legends-in-lattice.html#more
# https://stat.ethz.ch/pipermail/r-sig-geo/2014-September/021734.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment