如何在我的 ggplot 热图中获取标签?

How to get labels in my ggplot heatmap?

我想用实际值作为地图中的标签制作热图,但标签不显示。

这是我的数据:

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")

这是我的代码:

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)

我希望这会将值作为标签放在网格中:

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

但这并没有发生。为什么? 非常感谢。

(我被这个nicepost启发了)

ggplot 中的图层按书写顺序绘制。要在热图上方显示文本,geom_text() 调用应放在 geom_tile() 调用之后。

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