Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color axis text by variable

Tags:

r

ggplot2

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

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

How can I do this?

like image 784
JasonAment Avatar asked Apr 09 '14 19:04

JasonAment


1 Answers

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.

One way to do so would be something like this:

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])))
like image 175
Spencer Boucher Avatar answered Oct 24 '22 01:10

Spencer Boucher