# R - Creating a heatmap from scatterplot data

By | November 20, 2013

Here's the code and the image it produces. (Full explanation of each line is below)

```library(fields)
library(akima)
set.seed(1)

x <- runif(150)
y <- runif(150)
z <- c(rnorm(mean=1,100),rnorm(mean=20,50))
N <- length(x)

s <- interp(x,y,z,xo=seq(min(x),max(x),length=N),yo=seq(min(x),max(x),length=N),duplicate="mean")
image.plot(s,xlim=c(0,1),ylim=c(0,1),zlim=c(-2,25))
```

### For those that want the full tutorial, read from here:

Suppose you have some (x,y,z) data and wish to plot it. Perhaps you have weather data for a grid layout of a city. Whatever the data may be, it's common to look at three variables at once. At first thought, you may think to color code the (x,y) data based on the z value, so that you can examine the z dimension via color. But often, you'll want to smooth the data and get a better understanding for the trend. This is where a heatmap comes into play. The beauty of using the code below is that you get the legend on the right hand side for free. Here's the full code, with comments on each line:

```#We use the packages fields and akima. Let me know if you have trouble downloading these
library(fields)
library(akima)

#I'm just setting the seed so you can see the same example on your computer
set.seed(1)

#Our X data
x <- runif(150)

#Our Y data
y <- runif(150)

#Our Z data
z <- c(rnorm(mean=1,100),rnorm(mean=20,50))

#Store the length of our data
N <- length(x)

#Here is the interpolation to give the heatmap effect. Use xo and yo to set the output grid you want to use.
#xo and yo are used to change the resolution of the interpolation
#Here, I have included a somewhat standard protocol for these parameters
s <- interp(x,y,z,xo=seq(min(x),max(x),length=N),yo=seq(min(x),max(x),length=N),duplicate="mean")

#Here's where the fun happens
#Note you can add your typical plotting paramaters here, such as xlab or ylab
image.plot(s,xlim=c(0,1),ylim=c(0,1),zlim=c(-2,25))
```
Share
Send article as PDF