The Nightman
The Nightman

Reputation: 5759

Plot three grouped columns of data in R ggplot2

I have data that resembles the following:

Ref Var Obs 
A   A   2   
A   C   6   
A   T   8   
A   G   2   
C   A   9   
C   C   1   
C   T   8   
C   G   4   
T   A   6   
T   C   1   
T   T   9   
T   G   6   
G   A   3   
G   C   1   
G   T   7   
G   G   2

And I am trying to use qplot to plot the data but I'm not sure how to display three columns of information instead of just two, and in a grouped maner. I would like to plot a bar plot with number of obs on the y axis and var on the x-axis grouped by ref. The following is the idea of what I am trying to do:

example plot

Upvotes: 1

Views: 233

Answers (1)

agenis
agenis

Reputation: 8377

If I understood well your graphic, I suggest this:

Your data:

seq=c("A", "C", "T", "G")
df=data.frame('Ref'=rep(seq, each=4), 'Var'=rep(seq, 4), 'Obs'=rpois(16, 2))

The plot:

ggplot(data=df) + aes(x=Ref, group=Var, y=Obs) + geom_bar(stat='identity', position="dodge", fill="lightblue", color="black")     

Rendering:

enter image description here

Or if you need to see the complete axis legends, you can use the facetting:

ggplot(data=df) + aes(x=Var, y=Obs) + 
  geom_bar(stat='identity', position="dodge", fill="lightblue", color="black")  +
  facet_grid(~Ref)

enter image description here

last remark: if you want to change the order of the bars, just modify the levels of the factor variables.

Upvotes: 3

Related Questions