颜色轴文本按变量

时间:2014-04-09 19:43:02

标签: r ggplot2

我想根据数据集中的另一个变量来改变热图轴文本的颜色。这是我到目前为止所尝试的:

#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 $ label),x $ x,x $ y,:   无效的颜色名称&#39;地区&#39;

如果我删除&#39; Region&#39;周围的引号我收到这个错误:

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

我该怎么做?

1 个答案:

答案 0 :(得分:15)

不幸的是,通过theme访问的设置无法映射到美学等数据。您需要手动构建适当的颜色调色板(读取:列表)。

这样做的一种方法是:

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