This document explains how to use the
levelplot()
function of the lattice
R
package to build heatmaps.
The lattice
package allows to build
heatmaps thanks to the
levelplot()
function.
Input data: here input is a data frame with 3 columns prividing the X and Y coordinate of the cell and its value. (Long format).
Previous example of this document was based on a data frame at the
long format. Here, a square matrix is used instead. It is the
second format understood by the levelplot()
function.
Note: here row and column order isn’t respected in the heatmap.
The t()
function of R allows to transpose the input
matrix, and thus to flip X and Y coordinates.
Moreover, you can reverse matrix order as shown below to reverse order in the heatmap as well. Now the heatmap is organized exactly as the input matrix.
There are several ways to custom the color palette:
terrain.color()
,
rainbow()
, heat.colors()
,
topo.colors()
or cm.colors()
RColorBrewer
. See list of available
palettes here.
Viridis
: viridis, magma, inferno,
plasma.
# Lattice package
require(lattice)
# The volcano dataset is provided, it looks like that:
#head(volcano)
# 1: native palette from R
levelplot(volcano, col.regions = terrain.colors(100)) # try cm.colors() or terrain.colors()
# 2: Rcolorbrewer palette
library(RColorBrewer)
coul <- colorRampPalette(brewer.pal(8, "PiYG"))(25)
levelplot(volcano, col.regions = coul) # try cm.colors() or terrain.colors()
# 3: Viridis
library(viridisLite)
coul <- viridis(100)
levelplot(volcano, col.regions = coul)
#levelplot(volcano, col.regions = magma(100))
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥