I have a binary data set of 0 and 1, where 0 is an absence and 1 is a presence of an event.
A sample of the data set looks like this:
events germany Italy
Rain 0 1
hail 1 0
sunny 0 0
I'd like to get a red and white picture of this data in the form of heat map by reading the data from a file.
Edit: In response to comments below, here is a sample data file (saved on disk as "data.txt"):
Rain 0 0 0 0 1 0 1 0 0 1
Hail 0 1 0 0 0 0 0 1 0 0
Sunny 1 1 1 0 1 0 1 0 1 1
In python, we can read the labels and plot this "heatmap" by:
from numpy import loadtxt
import pylab as plt
labels = loadtxt("data.txt", usecols=[0,],dtype=str)
A = loadtxt("data.txt", usecols=range(1,10))
plt.imshow(A, interpolation='nearest', cmap=plt.cm.Reds)
plt.yticks(range(A.shape[0]), labels)
plt.show()
import pylab as plt

See ?image. With your data
dat <- data.matrix(data.frame(Germany = c(0,1,0), Italy = c(1,0,0)))
rownames(dat) <- c("Rain","Hail","Sunny")
This gets us close:
image(z = dat, col = c("white","red"))
but better handling of axis labels would be nice... Try:
op <- par(mar = c(5,5,4,2) + 0.1)
image(z = dat, col = c("white","red"), axes = FALSE)
axis(side = 1, labels = rownames(dat),
at = seq(0, by = 0.5, length.out = nrow(dat)))
axis(side = 2, labels = colnames(dat), at = c(0,1), las = 1)
box()
par(op)
Which gives

To have the heatmap the other way round, transpose dat (image(z = t(dat), ....)) and make in the axis() calls, change side to 2 in the first and 1 in the second call (and move the las = 1 to the other call. I.e.:
op <- par(mar = c(5,5,4,2) + 0.1)
image(z = t(dat2), col = c("white","red"), axes = FALSE)
axis(side = 2, labels = rownames(dat2),
at = seq(0, by = 0.5, length.out = nrow(dat2)), las = 1)
axis(side = 1, labels = colnames(dat2), at = c(0,1))
box()
par(op)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With