Conditional coloring of cells in table

A heatmap alternative:

library(gplots)

# need data as matrix
mm <- as.matrix(testdf, ncol = 3)

heatmap.2(x = mm, Rowv = FALSE, Colv = FALSE, dendrogram = "none",
          cellnote = mm, notecol = "black", notecex = 2,
          trace = "none", key = FALSE, margins = c(7, 11))

In heatmap.2 the side of the plot the axis is to be drawn on is hard-coded. But if you type “heatmap.2” at the console and copy the output to an editor, you can search for axis(1, where the 1 is the side argument (two hits). You can then change from a 1 (axis below plot) to a 3 (axis above the plot). Assign the updated function to a new name, e.g. heatmap.3, and run it as above.

enter image description here


An addtable2plot alternative

library(plotrix)

# while plotrix is loaded anyway:
# set colors with color.scale
# need data as matrix*
mm <- as.matrix(testdf, ncol = 3)
cols <- color.scale(mm, extremes = c("red", "yellow"))

par(mar = c(0.5, 1, 2, 0.5))
# create empty plot
plot(1:10, axes = FALSE, xlab = "", ylab = "", type = "n")

# add table
addtable2plot(x = 1, y = 1, table = testdf,
              bty = "o", display.rownames = TRUE,
              hlines = TRUE, vlines = TRUE,
              bg = cols,
              xjust = 2, yjust = 1, cex = 3)

# *According to `?color.scale`, `x` can be a data frame.
# However, when I tried with `testdf`, I got "Error in `[.data.frame`(x, segindex) : undefined columns selected".

enter image description here


A color2D.matplot alternative

library(plotrix)
par(mar = c(0.5, 8, 3.5, 0.5))
color2D.matplot(testdf, 
                show.values = TRUE,
                axes = FALSE,
                xlab = "",
                ylab = "",
                vcex = 2,
                vcol = "black",
                extremes = c("red", "yellow"))
axis(3, at = seq_len(ncol(testdf)) - 0.5,
     labels = names(testdf), tick = FALSE, cex.axis = 2)
axis(2, at = seq_len(nrow(testdf)) -0.5,
     labels = rev(rownames(testdf)), tick = FALSE, las = 1, cex.axis = 2)

enter image description here

After this little exercise, I tend to agree with @Drew Steen that LaTeX alternatives may be investigated as well. For example, check here and here.

Leave a Comment