R 按变量显示颜色轴文本

R 按变量显示颜色轴文本,r,ggplot2,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

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

#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

我该怎么做

通过
主题访问的设置无法映射到数据,例如。您需要手动构建一个合适的调色板(读取:列表)

一种方法是这样:

library(scales)
numColors <- length(levels(melted_state$Region)) # How many colors you need
getColors <- scales::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])))
库(比例)

NumColor很有趣,但我认为这是
ggplot2
作者没有考虑的一个灵活性轴,因此这可能很难做到。当标签顺序与因子顺序不匹配时(例如在ggplot中重新排序标签或使用面时),有没有关于如何进行此操作的建议。有没有办法从ggplot对象中提取标签的顺序?我总是用一个因子来设置变量的顺序。如果你事先做这件事,你应该是个好人。你可以从ggplot对象中提取
中断
信息,但这有点痛苦。。。
library(scales)
numColors <- length(levels(melted_state$Region)) # How many colors you need
getColors <- scales::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])))