[R] [HELP] Setting plot colors such that category/color mapping persists across plots

Jim Lemon jim at bitwrit.com.au
Sat Jun 28 02:07:55 CEST 2014


On Thu, 26 Jun 2014 07:34:15 PM Kellyn Wolff wrote:
> Hi all,
> 
> I'm creating a set of stacked bar charts, where each bar is colored 
by
> a category.  The problem I'm having is that a given category is being
> represented by different colors across plots (category A might be 
red
> in one plot and blue in another).  This is because the number of
> categories in a given plot may change, thus getting a different color
> assignment from R.
> 
> My thought was that I could create a column with the hexadecimal 
value
> for the color I want in each category, and then somehow specify in 
the
> plot that I want it to choose the color specified in that column.
> There may be a better way.
> 
> I am using RStudio 0.98.945 on Windows 7 64 bit.  I've pasted some
> example code below to illustrate the issue I'm having.  You will
> notice that categories D, E and F in "plottest2" have different colors
> than they do in "plottest".  I want colors for a given category to
> persist across plots.
> 
> TestData <- data.frame(rep(c("A","B","C","D","E","F"), each=10),
> rep(1:10, 6), rnorm(6, 60, 10)*rep(1:10, 6))
> names(TestData) <- c("category", "timeline", "rollup")
> 
> library(ggplot2)
> plottest <- ggplot(TestData, aes(as.factor(timeline), rollup, 
category))
> plottest + geom_bar(stat="identity", aes(fill=category)) +
> labs(title="Test rollup data over time") +
>   labs(x = "Time measure") + labs(y = "Frequency Totals") +
> theme(axis.text.x = element_text(angle = 45, hjust = 1))
> 
> 
> plottest2 <- ggplot(subset(TestData, category == "D" | category 
== "E"
> 
> | category == "F"), aes(as.factor(timeline), rollup, category))
> 
> plottest2 + geom_bar(stat="identity", aes(fill=category)) +
> labs(title="Test rollup data over time subsetted") +
>   labs(x = "Time measure") + labs(y = "Frequency Totals") +
> theme(axis.text.x = element_text(angle = 45, hjust = 1))
> 
Hi Kellyn,
A useful strategy is to generate a set of colors for all categories, and 
then apply the same subsetting criterion to both categories and colors 
for each plot:

testmat<-matrix(TestData$rollup,nrow=6,byrow=TRUE)
rownames(testmat)<-levels(TestData$category)
barplot(testmat,col=testcol)
rowsDE<-rownames(testmat) %in% c("D","E")
barplot(testmat[rowsDE,],col=testcol[rowsDE])

My apologies, but I couldn't quite work out where to put the color 
argument in ggplot2. However, this trick should work in ggplot2.

Jim



More information about the R-help mailing list