Barplot with 3 categorical variables

I have 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 barplot

with beside = TRUE

and beside = FALSE

( TRUE

for Cat

and Comp

and FALSE = Type

).

Using this data, a graph with 8 columns will be displayed (interaction Comp

with Cat

( Comp = 2003 + Cat = A ; Comp = 2003 + Cat = B ; ... ; Comp = 2004 + Cat = D

)), each of which has two columns (levels Type

( Free

and Used

)) for a variable Count

.

Any advice how can I make a plot like this? I tried to do an example in EXCEL, but I also failed.

+3


source to share


2 answers


Similarly in ggplot2

:

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

      



To group 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)

      

+4


source


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 comment:

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

      

enter image description here

+4


source







All Articles