[R] [HELP] Setting plot colors such that category/color mapping persists across plots
Kellyn Wolff
kellyn.b.wolff at gmail.com
Fri Jun 27 04:34:15 CEST 2014
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))
This is my first post to this group, so I hope I've followed the
posting guidelines appropriately. Please advise if there is anything
I can do to make this more helpful.
Thanks in advance!
-KW
More information about the R-help
mailing list