如何指定"低"和"高"并使用scale_fill_gradient在两端获得两个刻度

时间:2014-10-15 16:37:40

标签: r colors ggplot2 scale heatmap

我的问题是我希望使用geom_tile为我的热图提供不同的颜色,并且渐变颜色在比例的两端都有所不同。例如,整个比例为(-1,1),我只想要-1到-0.5之间的值,0.5到1.0之间的值具有渐变颜色变化,-0.5和0.5之间的值保持为白色。但是,我无法在scale_fill_gradient中找到可以达到目标的选项。可重现的示例如下,数据来自ggplot2 heatmaps: using different gradients for categories

nba <- read.csv("http://datasets.flowingdata.com/ppg2008.csv")
nba$Name <- with(nba, reorder(Name, PTS))

library("ggplot2")
library("plyr")
library("reshape2")
library("scales")

nba.m <- melt(nba)
nba.s <- ddply(nba.m, .(variable), transform,
               rescale = scale(value))

ggplot(nba.s, aes(variable, Name))+geom_tile(aes(fill = rescale), colour = "white") + 
scale_fill_gradient(low = "darkgreen", high = "darkred") 

1 个答案:

答案 0 :(得分:10)

您可以尝试将白色中点添加到scale_fill_gradient2

gg <- ggplot(nba.s, aes(variable, Name))
gg <- gg + geom_tile(aes(fill = rescale), colour = "white")
gg <- gg + scale_fill_gradient2(low = "darkgreen", mid = "white", high = "darkred")
gg <- gg + labs(x="", y="")
gg <- gg + theme_bw()
gg <- gg + theme(panel.grid=element_blank(), panel.border=element_blank())
gg

enter image description here

但是,如果您按照链接到的SO帖子中的答案并使用scale_fill_gradientn,那么您将拥有最大的灵活性。

编辑(显示评论讨论中的示例)

# change the "by" for more granular levels

green_seq <- seq(-5,-2.000001, by=0.1)
red_seq <- seq(2.00001, 5, by=0.1)

nba.s$cuts <- factor(as.numeric(cut(nba.s$rescale, 
                             c(green_seq, -2, 2, red_seq), include.lowest=TRUE)))

# find "white"
white_level <- as.numeric(as.character(unique(nba.s[nba.s$rescale >= -2 & nba.s$rescale <= 2,]$cuts)))
all_levels <- sort(as.numeric(as.character(unique(nba.s$cuts))))

num_green <- sum(all_levels < white_level)
num_red <- sum(all_levels > white_level)

greens <- colorRampPalette(c("#006837", "#a6d96a"))
reds <- colorRampPalette(c("#fdae61", "#a50026"))

gg <- ggplot(nba.s, aes(variable, Name))
gg <- gg + geom_tile(aes(fill = cuts), colour = "white")
gg <- gg + scale_fill_manual(values=c(greens(num_green),
                                      "white", 
                                      reds(num_red)))
gg <- gg + labs(x="", y="")
gg <- gg + theme_bw()
gg <- gg + theme(panel.grid=element_blank(), panel.border=element_blank())
gg <- gg + theme(legend.position="bottom")
gg

enter image description here

传说远非理想,但您可以通过其他方式将其排除或解决它。