Plot a regular 2D plot, but add a 3D dimension as a heatmap
Couldn't find what I'm asking, possibly wrong keywords. Essentially I have 3 dimensions in a matrix:
> head(info)
[,1] [,2] [,3]
[1,] 8.59645 251944 22.89
[2,] 6.95160 141559 21.35
[3,] 7.43870 131532 22.99
[4,] 8.64467 126688 22.72
[5,] 8.77482 123120 22.17
[6,] 7.22364 122268 24.46
I am drawing information [, 3] vs info [, 2]
plot(info[,3], info[,2], type="p", pch=20)
And I wanted to color the points with a heatmap based on information [, 1].
I could just do things like this:
plot(info[which(info[,1] <= 2),3], info[which(info[,1] <= 2),2], type="p", pch=20, col="black")
lines(info[which(info[,1] >= 2),3], info[which(info[,1] >= 2),2], type="p", pch=20, col="red")
But I believe the heat map will look better.
Any ideas? Thanks, Adrian
SOLUTION: Thanks everyone for the great suggestions! Here's what worked:
qplot(info[,3], info[,2], colour=info[,1]) + scale_colour_gradient(limits=c(0, 10), low="green", high="red")
+3
source to share
1 answer
Using ggplot2
, you can mark the third variable
## Some sample data
set.seed(0)
x <- rnorm(1000, rep(c(20, 60), each=500), 8)
y <- c(rexp(500, 1/5e4)*1/(abs(x[1:500]-mean(x[1:500]))+runif(1)),
rexp(500, 1/5e3)*1/(abs(x[501:1000]-mean(x[501:1000]))+runif(1)))
z <- c(sort(runif(1000)))
info <- matrix(c(z,y,x), ncol=3)
## Using ggplot
ggplot(as.data.frame(info), aes(V3, V2, col=V1)) +
geom_point(alpha=0.5) +
scale_color_gradient(low="red", high="yellow")
If you want to create a heat map, you can use the package akima
to interpolate between your points and do
library(akima)
dens <- interp(x, y, z,
xo=seq(min(x), max(x), length=100),
yo=seq(min(y), max(y), length=100),
duplicate="median")
filled.contour(dens, xlab="x", ylab="y", main="Colored by z",
color.palette = heat.colors)
+6
source to share