按变量对颜色轴文本进行着色

17

我想根据数据集中的另一个变量来改变热力图轴标签的颜色。目前我尝试了以下方法:

#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, : 非法的颜色名称 'Region'
如果我去掉 'Region' 周围的引号,我会得到以下错误:
Error in structure(list(family = family, face = face, colour = colour,  : 
  object 'Region' not found
我该怎么做呢?

有趣的是,我认为这是ggplot2作者没有考虑到的一种灵活性轴,因此可能很难实现。 - Ben Bolker
1个回答

19

通过 theme 访问的设置无法像美学一样被映射到数据上。不幸的是,您需要手动构建一个适当的调色板(即列表)。

其中一种方法是这样的:

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

4
当标签的顺序与因子的顺序不匹配时(例如在ggplot中重新排序标签或使用facet时),有什么建议可以解决这个问题?是否有一种方法可以从ggplot对象中提取标签的顺序? - Etienne Low-Décarie
我总是用因子设置变量的顺序。如果你提前这样做,应该就没问题了。你可以从 ggplot 对象中提取 breaks 信息,但有点麻烦... - Nate
使用最新版本的ggplot(ggplot2_3.4.0)目前还不支持:向`element_text()`提供矢量输入尚未得到官方支持。 - jgarces

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接