-2

I have the below data in a data.frame

Count   Group A Group B
2   Red One 
1   Blue    One 
1   Green   One 
5   Red Two
1   Blue    Two
2   Red Three
4   Blue    Three
2   Green   Three
1   Yellow  Three

I need to plot this in a way similar to this enter image description here

How can I do that? Thanks!

Diego Quirós
  • 898
  • 1
  • 14
  • 28
  • Take a look at `?xtabs` to create a frequency table on `count` and `?barplot` with `beside=TRUE` set to get your barplot. – thelatemail Feb 18 '16 at 04:32
  • 1
    Possible duplicate of [Creating a grouped bar plot in R](http://stackoverflow.com/questions/20985284/creating-a-grouped-bar-plot-in-r) – Jonathan Carroll Feb 18 '16 at 04:33
  • If I am not mistaken, these bars are not stacked. –  Feb 18 '16 at 04:58
  • Jonathan I tried it, but this is slightly different cause entries in the examples are all numeric, but I have non-numeric groups. So it gave me Error in -0.01 * height : non-numeric argument to binary operator – Diego Quirós Feb 18 '16 at 14:22
  • this is very similar to http://stackoverflow.com/questions/13210152/plotting-grouped-bar-charts-in-r – Marcus D Feb 18 '16 at 21:12

1 Answers1

1

Reading in your data;

df <- read.table(text="Count Group_A Group_B
2 Red One
1 Blue One
1 Green One
5 Red Two
1 Blue Two
2 Red Three
4 Blue Three
2 Green Three
1 Yellow Three", sep=" ", header=TRUE)

Specifying the level ordering of factors;

df$Group_A <- factor(df$Group_A, levels=c("Red", "Blue", "Green", "Yellow"))
df$Group_B <- factor(df$Group_B, levels=c("One", "Two", "Three"))

Creating a barplot;

library(ggplot2)
ggplot(df) + 
  geom_bar(aes(x=Group_B, y=Count, fill=Group_A), position="dodge", stat="identity") + 
  scale_fill_manual(values=c("Red"="red", "Blue"="blue", "Green"="green","Yellow"="yellow"))

enter image description here

Alternatively, if you don't want the uneven groups to have different widths, I'd add in the missing data;

df <- read.table(text="Count Group_A Group_B
2 Red One
1 Blue One
1 Green One
5 Red Two
1 Blue Two
2 Red Three
4 Blue Three
2 Green Three
1 Yellow Three
0 Yellow One
0 Green Two
0 Yellow Two", sep=" ", header=TRUE)

enter image description here

For an even closer representation of what you requested;

ggplot(df) + 
  geom_bar(aes(x=Group_B, y=Count, color=Group_A), fill="white", width=0.3, position=position_dodge(width=0.5), stat="identity", lwd=2)     + 
  scale_color_manual(values=c("Red"="red", "Blue"="blue", "Green"="green", "Yellow"="yellow")) + theme_bw() 

enter image description here

Jonathan Carroll
  • 3,897
  • 14
  • 34