Hi Jim,
In most cases, I would highly recommend an alternative to a stacked
bar plot (only 4 numbers are communicated, but an entire plot is
filled). Depending on the data and your goals, simple points or lines
offer easy alternatives. I have also been able to get a lot of
mileage out of facetting graphics. In any case, if you are sure a
stacked bar chart is best for your situation, here is a solution using
the ggplot2 package:
x = matrix(c(5,2,3,1),nrow=2)
require(ggplot2)
ggplot(data = melt(x), aes(x = X2, y = value)) +
geom_bar(aes(fill = interaction(X1, X2)), stat = "identity") +
scale_fill_manual(name = "Example", values = c("black",
"red",
"blue", "green"))
note that if you are content to let ggplot2 pick the default colours,
there is no need for the scale_fill_manual line.
## Example using faceting
## suddenly it does not seem like much information is being conveyed
ggplot(data = melt(x), aes(x = X2, y = value)) +
geom_point(aes(colour = interaction(X1, X2)), size = 4) +
geom_line() +
facet_grid(. ~ X1) # highlight absolute difference
## facet the other way to highlight the relative difference rather
than the fact that facet 1 is absolutely higher
ggplot(data = melt(x), aes(x = X2, y = value)) +
geom_point(aes(colour = interaction(X1, X2)), size = 4) +
geom_line() +
facet_grid(X1 ~ .) # highlight difference between slopes
Hope this helps,
Josh
On Sun, Jul 24, 2011 at 4:50 PM, James Fearon <jfearon at stanford.edu>
wrote:> Hi,
>
> In barplot(height, col = ...), the col = vector recycles so that the same
> colors are used for each bar. ?I would like to use different colors in
> different bars (corresponding to another piece of information, here, the
> region of the country being represented).
>
> For example,
>
> x = matrix(c(5,2,3,1),nrow=2)
> barplot(x,col=1:4)
>
> will draw two bars with two segments each, but each colored red and black
> rather than red and black for the first bar, then green and blue for the
> second.
>
> I see in the archives that someone asked this question before, and got a
> single reply (as far as I could tell) suggesting that s/he forget barplot
> and use rect(). ?That's kind of a pain, so I'm wondering if there
is any
> simpler way of tricking barplot() into doing this.
>
> Thanks,
>
> Jim Fearon
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
https://joshuawiley.com/