如何根据填充值动态,优雅地改变geom_text的颜色

时间:2015-09-01 02:28:40

标签: r ggplot2 heatmap

我有这个热图,每个瓷砖都添加了值标签

require(ggplot2)
require(RColorBrewer)
require(dplyr)

jBuPuFun <- colorRampPalette(brewer.pal(n = 9, "BuPu"))
paletteSize <- 256
jBuPuPalette <- jBuPuFun(paletteSize)

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
nba$Name <- with(nba, reorder(Name, PTS))
nba.m <- melt(nba)
nba.m <- ddply(nba.m, .(variable), transform,
               rescale = rescale(value))

ggplot(nba.m, aes(variable, Name)) + 
  geom_tile(aes(fill = rescale), colour = "white") + 
  scale_fill_gradient2(low = jBuPuPalette[1],
                       mid = jBuPuPalette[paletteSize/2],
                       high = jBuPuPalette[paletteSize],
                       midpoint = 0.5) +
  geom_text(aes(fill = rescale, label = round(rescale, 1)), colour = "white")

然而,标签保持均匀的颜色(白色),这使得当背景也很轻时难以阅读。

enter image description here

是否有任何优雅的方法可根据填充值动态定义每个geom_text的颜色?

1 个答案:

答案 0 :(得分:1)

如果您在填充的反面着色文本,则可以获得不错的结果。我将反向着色的中点改为&#34; steelblue&#34;因为如果你不在那里调整颜色,那么颜色很难在中点区分。

p <- ggplot(nba.m, aes(variable, Name)) + 
  geom_tile(aes(fill = rescale), color="white") + 
  scale_fill_gradient2(low = jBuPuPalette[1],
                       mid = jBuPuPalette[paletteSize/2],
                       high = jBuPuPalette[paletteSize],
                       midpoint = 0.5) +
  scale_color_gradient2(low = jBuPuPalette[paletteSize],
                       mid = "steelblue",
                       high = jBuPuPalette[1],
                       midpoint = 0.5) +
  geom_text(aes(fill = rescale, color=rescale, label = round(rescale, 1)))