Matrix plots in R: a neat way to display three variables

I’ve decided to share a neat way of plotting data; something I’ve used a number of times for my own projects. There may already be R packages out there which have functions to produce matrix plots, but it never hurts to know how to use base R plotting functions to get the job done.
In a nutshell a matrix plot lets you display three variables on a x-y axis: the x and y axis form a “grid” and each “cell” of the grid is colored based on the magnitude of a third variable. In the past, I’ve used a matrix plot with a time series of correlation coefficients. The y-axis was dates, the x-axis was different independent variables, and the color of each “cell” was the magnitude of correlation. Maybe my next post will demonstrate how to plot dates on the the y or x-axis. Also, feel free to mess around with rgb() function to learn how it changes the color scheme!

### Create Matrix plot using colors to fill grid
# Create matrix.   Using random values for this example.
rand <- rnorm(286, 0.8, 0.3)
mat <- matrix(rand, nrow = 26)
dim(mat)  # Check dimensions

# Create x and y labels
yLabels <- seq(1, 26, 1)
xLabels <- c("a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k");

# Set min and max values of rand
 min <- min(rand, na.rm=T)
 max <- max(rand, na.rm=T)

# Red and green range from 0 to 1 while Blue ranges from 1 to 0
 ColorRamp <- rgb(seq(0.95,0.99,length=50),  # Red
                  seq(0.95,0.05,length=50),  # Green
                  seq(0.95,0.05,length=50))  # Blue
 ColorLevels <- seq(min, max, length=length(ColorRamp))

# Set layout.  We are going to include a colorbar next to plot.
layout(matrix(data=c(1,2), nrow=1, ncol=2), widths=c(4,1),
#plotting margins.  These seem to work well for me.
par(mar = c(5,5,2.5,1), font = 2)

# Plot it up!
image(1:ncol(mat), 1:nrow(mat), t(mat),
	 col=ColorRamp, xlab="Variable", ylab="Time",
	 axes=FALSE, zlim=c(min,max),
	 main= NA)

# Now annotate the plot
axis(side = 1, at=seq(1,length(xLabels),1), labels=xLabels,
axis(side = 2, at=seq(1,length(yLabels),1), labels=yLabels, las= 1,

# Add colorbar to second plot region
par(mar = c(3,2.5,2.5,2))
 image(1, ColorLevels,
      matrix(data=ColorLevels, ncol=length(ColorLevels),nrow=1),
      col=ColorRamp,xlab="",ylab="",xaxt="n", las = 1)

Matrix Plot (color Bar represents third variable)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s