2015-09-01 114 views
2

我有這樣的熱圖與值標籤添加到每個瓷磚如何基於填充值

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

儘管如此標籤保持均勻的顏色(白色),這使得它們難以閱讀時geom_text的動態和典雅的變色背景也很輕。

enter image description here

是否有任何優雅的方式來動態地定義每個geom_text的基礎上,填充值的顏色?

回答

1

如果您在填充的背面着色文本,您可以獲得不錯的結果。我將反向着色的中點改爲「鋼藍」,因爲如果你不在那裏調整顏色,中點處的顏色將難以區分。

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