[R] juxtaposed and stacked bars in one barplot?

hadley wickham h.wickham at gmail.com
Thu Aug 28 17:49:18 CEST 2008


On Thu, Aug 28, 2008 at 9:31 AM, Stefan Uhmann
<stefan.uhmann at mailbox.tu-dresden.de> wrote:
> hadley wickham schrieb:
>>
>> Hi Stefan,
>>
>> Could you be a bit more explicit?  Do you have an example dataset that
>> you are trying to visualise?
>>
>
> Right, thanks for pointing out the obvious.
>
> So here's my code:
>
>>>
> library(gplots)
>
> quarter <- as.factor(sample(c("Q1", "Q2", "Q3", "Q4"),
>        100, replace = TRUE))
> year <- as.factor(sample(c(seq(from=2000, to=2008)), 100, replace = TRUE))
> category <- as.factor(sample(c(seq(from=1, to=4)), 100, replace = TRUE))
> test <- data.frame(quarter, year, category)
> table(test$category, test$quarter, test$year)
> barplot2(table(test$quarter, test$year),
>    beside=T, ylim=c(0,10), main="how to include dim3?")
> # inclusion of 3rd dimension does not work:
> barplot2(table(test$quarter, test$year, test$category),
>    beside=T, ylim=c(0,10), main="how to include dim3?")
> <<
>
> I want the barplot to be exactly the same but with the bars stacked (by
> 'category'). I got the message from Gaspar, but have not yet tried to fit
> his example to my data.

Hi Stefan,

For your data, I'd suggest you consider using lines instead of bars.
http://peltiertech.com/WordPress/2008/08/27/stacked-vs-clustered/ has
some good reasons why. - but basically stacking makes it difficult to
see how each group changes over time.  It's pretty easy to play around
different variations with ggplot2, so I've included a few you might
want to look at.  (Including your original request right at the
bottom)

test <- data.frame(quarter, year, category)
tabdf <- as.data.frame(with(test, table(category, quarter, year)))

install.packages("ggplot2")
qplot(year, Freq, data=tabdf, geom="line", colour = category, facets =
 quarter ~ . , group = interaction(category, quarter))
# OR
qplot(year, Freq, data=tabdf, geom="line", colour = quarter, facets =
category ~ . , group = interaction(category, quarter))

# If you _really_ want stacking:

qplot(year, Freq, data=tabdf, geom="area", fill = quarter, facets =
category ~ . , group = interaction(category, quarter))

# OR

qplot(year, Freq, data=tabdf, geom="bar", stat="identity", fill =
quarter, facets =  category ~ .)

# OR finally, like what you originally asked for

qplot(quarter, Freq, data=tabdf, geom="bar", stat="identity", fill =
category, facets = . ~ year)


Regards,

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list