2014-04-09 4 views
10

데이터 세트의 다른 변수에 따라 히트 맵 축 텍스트의 색을 변경하고 싶습니다. 변수로 색 축 텍스트

#load data, scale numeric columns, add state abbreviation and region 
state_data <- data.frame(state.x77) 
state_data <- state_data[,1:8] 
state_data <- rescaler(state_data, type='range') 
state_data$State <- state.abb 
state_data$Region <- state.region 

#make heatmap 
melted_state <- melt(state_data,id.vars=c('State', 'Region')) 

p <- ggplot(melted_state, 
     aes(x=State, y=variable)) 
p <- p + geom_tile(aes(fill = value), colour = "white") 
p <- p + theme(axis.text.x=element_text(colour="Region")) ## doesn't work! 
p 

내가이 오류를 얻을 : 이것은 내가 지금까지 시도한 것입니다 grid.Call (L_textBounds에서 오류, as.graphicsAnnot (X의 $ 라벨)의 X $의 X, X의 $ y를, : 잘못된 색 이름 '지역'

내가 '지역'주위에 따옴표를 제거하면이 오류 얻을 : 나는이 작업을 수행 할 수있는 방법

Error in structure(list(family = family, face = face, colour = colour, : 
    object 'Region' not found 

+0

재미있는, 그러나 나는 이것이'ggplot2' 저자 (들)에 의해 고려되지 유연성의 축 생각, 그래서 어려울 수 있습니다 해야 할 것. –

답변

11

설정를 통해 액세스를?은 불행히도 미학과 같은 데이터에 매핑 될 수 없습니다. 적절한 팔레트 (읽기 : 목록)를 수동으로 생성해야합니다. 그렇게 할

한 가지 방법은 다음과 같이 될 것이다 :

numColors <- length(levels(melted_state$Region)) # How many colors you need 
getColors <- brewer_pal('qual') # Create a function that takes a number and returns a qualitative palette of that length (from the scales package) 
myPalette <- getColors(numColors) 
names(myPalette) <- levels(state_data$Region) # Give every color an appropriate name 
p <- p + theme(axis.text.x = element_text(colour=myPalette[state_data$Region]))) 
+2

라벨의 순서가 요인의 순서와 일치하지 않을 때 (예 : 라벨이 ggplot에서 재정렬되거나 패싯을 사용할 때)이 작업 방법에 대한 제안. ggplot 객체에서 레이블의 순서를 추출하는 방법이 있습니까? –