本文介绍了色轴文字按变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想根据数据集中的另一个变量来更改热图轴文本的颜色.到目前为止,这是我尝试过的:
I'd like to vary the color of my heatmap axis text depending on another variable in the dataset. This is what I've tried so far:
#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,中的错误: 无效的颜色名称区域"
I get this error:Error in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : invalid color name 'Region'
如果我删除区域"周围的引号,则会出现此错误:
And if I remove the quotes around 'Region' I get this error:
Error in structure(list(family = family, face = face, colour = colour, :
object 'Region' not found
我该怎么做?
推荐答案
不幸的是,无法将通过theme
访问的设置映射到数据.您将需要手动构建适当的颜色调色板(读取:列表).
Settings accessed via theme
cannot be mapped to the data like aesthetics unfortunately. You will need to construct an appropriate palette (read: list) of colors manually.
这样做的一种方法是:
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])))
这篇关于色轴文字按变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!