2014-04-09 31 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對象中提取標籤的順序? –