3

I have a data like this:

data <- data.frame(Comp = factor(rep(2003:2004, each = 8)), 
                   Cat = rep(letters[1:4], 4), 
                   Type = rep(c('Free','Used'), each = 4), 
                   Count = trunc(rnorm(16,30,2)))

And I need something like a barplot with beside = TRUE and beside = FALSE (TRUE for Cat and Comp, and FALSE = Type).

With this data, it will result a plot with 8 columns (Interaction of Comp with Cat (Comp = 2003 + Cat = A ; Comp = 2003 + Cat = B ; ... ; Comp = 2004 + Cat = D)), each one with 2 stacked columns (the levels of Type (Free and Used)) for Count variable.

Any tip how can I do this kind of plot? I tried to do an example in EXCEL, but I failed on it too.

Rcoster
  • 3,170
  • 2
  • 16
  • 35

2 Answers2

4

In lattice:

 barchart(Count~interaction(Cat,Comp),groups=Type,data=data,auto.key=T,stack=T)

enter image description here

Another way to group, from the comment:

barchart(Count~Cat|factor(Comp),groups=Type,data=data,auto.key=T,stack=T)

enter image description here

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • Almost there! You know if there is any option to group the bars of `Cat` for each `Comp`? Like this: `barplot(VADeaths, beside = TRUE)` – Rcoster Feb 18 '13 at 16:04
  • Thanks dude! One last question: There is an easy way to write the value in the middle of each bar? – Rcoster Feb 18 '13 at 16:25
4

Similarly in ggplot2:

ggplot(data, aes(x=interaction(Cat, Comp), y=Count, fill=Type)) +   
  geom_bar(position='stack', stat='identity')

To group on an additional variable (or two) you can use facet_wrap or facet_grid.

ggplot(data, aes(x=Cat, y=Count, fill=Type)) +   
  geom_bar(position='stack', stat='identity') +
  facet_wrap( ~ Comp)
Justin
  • 42,475
  • 9
  • 93
  • 111
  • Same question: You know if there is any option to group the bars of `Cat` for each `Comp`? Like this: `barplot(VADeaths, beside = TRUE)` – Rcoster Feb 18 '13 at 16:06
  • Exactaly! One last question: There is an easy way to write the value in the middle of each bar? – Rcoster Feb 18 '13 at 16:22
  • Please try not to amend questions with more and more questions :) take a look at [this post](http://stackoverflow.com/questions/14941940/r-stacked-bar-graph-plotting-geom-text). While not answered, Joran's comment should make it clear whats needed. – Justin Feb 18 '13 at 19:06