颜色轴文本按变量

Jas*_*ent 13 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
Run Code Online (Sandbox Code Playgroud)

我收到此错误: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
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Spe*_*her 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])))
Run Code Online (Sandbox Code Playgroud)

  • 当标签的顺序与因子的顺序不匹配时(例如,在ggplot中重新排序标签或使用facet时),如何处理此任何建议.有没有办法从ggplot对象中提取标签的顺序? (4认同)