Tiago Bruno
Tiago Bruno

Reputation: 413

How to make a barplot with ggplot2 with 3 groups?

I have a dataset like these:

 "term" "Col_count" "JG_count" "Mix_count"
 "1" "activation of immune response" 79 38 84
 "2" "adaptive immune response" 79 41 80
 "3" "adaptive immune response2" 73 40 74
 "4" "biological adhesion" 158 115 195
 "5" "cell activation" 167 103 193

I have 3 groups (columns 2:4) and 1 category for each group.

I need to make a barplot with each of these category grouping the 3 groups like in this picture, using ggplot2: enter image description here

Can Someone help me?

Upvotes: 2

Views: 2991

Answers (1)

Rorschach
Rorschach

Reputation: 32466

The function you need is interaction to create a combination variable of the three other variables that you can use as a grouping factor.

## First reshape the data
library(reshape2)
dat <- melt(dat)

## use the interaction between the variables to define the grouping
ggplot(dat, aes(term, value, fill=interaction(variable))) +
  geom_bar(stat='identity', position='dodge') +
  theme_bw() + theme(axis.text.x = element_text(angle=90, hjust=1)) +
  scale_fill_brewer('Variables', palette='Spectral')

enter image description here

Upvotes: 1

Related Questions