2014-10-15 4 views
6

제 질문은 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"낮은"및 "높음"을 지정하고 scale_fill_gradient를 사용하여 두 끝의 두 배율을 얻는 방법

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

답변

8

에서 당신은 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

을하지만, 당신이 연결된 게시물에 답을 따르고 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

전설 멀리 이상적에서,하지만 당신은 잠재적으로 다른 수단을 통해 또는 주위 작업을 제외 할 수 있습니다 .

+0

답변 해 주셔서 감사합니다. 그러나이 경우에는 -2에서 2까지의 모든 값을 모두 그래디언트 효과없이 흰색으로 지정해야합니다. – MYjx

+0

이 방법과'gradientn' 솔루션이 작동하지 않으면 값을 자체적으로''자르고''scale_fill_manual''로 그라디언트 색상을 수동으로 지정하십시오. – hrbrmstr

+0

옙'scale_fill_manual'을 사용해 보았지만 매일 많은 양의 데이터를 저장할 때마다 색상을 지정하고 싶지 않습니다. 그래서'gradientn'을 사용하고 싶습니다. 나는 'breaks'를 사용하려고 시도했으나 컬러 자체가 아니라 전설에서 작동하는 것처럼 보인다. – MYjx