rdatasculptor rdatasculptor - 5 days ago 7
R Question

How to get labels in my ggplot heatmap?

I want to make a heatmap with the actual values as labels in the map, but the labels don't show.

Here's my data:

df <- structure(list(a = c(0.39, 0.26, 0.39, 0.45, 0.41, 0.42, 0.42, 0.34, 0.36, 0.22, 0.34, 0.08, 0.18, 0.3, 0.29, 0.23, 0.31, 0.1, 0.28, 0.19, 0.13, 0.27, 0.33, 0.37), b = c(0.24, 0.22, 0.22, 0.35, 0.22, 0.29, 0.2, 0.19, 0.3, 0.33, 0.31, -0.11, 0.13, 0.25, 0.39, 0.33, 0.48, 0.38, 0.55, 0.21, 0.42, 0.48, 0.29, 0.55), c = c(0.29, 0.18, 0.24, 0.27, 0.27, 0.43, 0.31, 0.32, 0.3, 0.28, 0.3, 0.06, 0.18, 0.21, 0.32, 0.27, 0.37, 0.21, 0.47, 0.1, 0.23, 0.45, 0.36, 0.56), d = c(0.1, 0.03, 0.22, 0.21, 0.16, 0.4, 0.37, 0.35, 0.59, 0.59, 0.63, 0.31, 0.56, 0.55, 0.67, 0.63, 0.57, -0.05, 0.23, 0.34, 0.01, 0.37, 0.25, 0.26), `Item` = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 14L, 22L, 23L), .Label = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "w", "x"), class = "factor")), .Names = c("a", "b", "c", "d", "Item"), row.names = c(NA, 24L), class = "data.frame")df.m <- melt(df, id="Item", variable.name="Scale", value.name="Correlation")


Here's my code:

library(ggplot2)
library(grid)

ggplot(df.m, aes(Scale, Item, fill=abs(Correlation))) +
geom_text(aes(label = round(Correlation, 2)), size=2.5) +
geom_tile() +
theme_bw(base_size=10) +
theme(axis.text.x = element_text(angle = 90),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
plot.margin = unit(c(3, 1, 0, 0), "mm")) +
scale_fill_gradient(low="white", high="blue") +
guides(fill=F)


I expect this to put the value as a label in the grid:

geom_text(aes(label = round(Correlation, 2)), size=2.5)


But it doesn't happen. Why?
Many thanks in advance.

(I was inspired by this nice post)

Answer

Layers in the ggplot are plotted in order as they are written. To display text above the heatmap the geom_text() call should be place after geom_tile() call.

  .....
  geom_tile() +
  geom_text(aes(label = round(Correlation, 2)), size=2.5) + 
  .....
Comments