Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create barplot from data.frame

Tags:

dataframe

plot

r

In R I have a data.frame like the one on the top of the picture.

Is there a possibility to create a barplot like below?

data.frame:

      X1   X2   X3  
 --- ---- ---- ---- 
  A    2   3    4   
  B    4   2    1   
  C    1   NA   NA  

Barplot:

----------------------------
|                          |
|       #    #             |
|    #  #    #             |
| #  #  #    #  #          |
| #  #  #    #  #  #    #  |
----------------------------
  X1 X2 X3   X1 X2 X3   x1
     A           B       C
like image 569
ElPatzo Avatar asked May 17 '13 20:05

ElPatzo


2 Answers

Using base graphics you can do this simply:

mydf <- data.frame( X1=c(A=2, B=4, C=1), X2=c(3,2,NA), X3=c(4,1,NA) )
barplot(t(as.matrix(mydf)), beside=TRUE)

Using additional calls to axis can give the labeling more like in the question.

like image 120
Greg Snow Avatar answered Nov 06 '22 22:11

Greg Snow


Assuming, that you don't want ascii output, here is a solution using ggplot2:

# load / generate your data
mydf <- data.frame( X1 = c(2,4,1), X2 = c(3,2,NA), x3 = c(4,1,NA), row.names=c("A","B","C") )
mydf$Category  <- row.names(mydf)

# bring your data to long format as needed by ggplot
library(reshape2)
mydf.molten <- melt(mydf, value.name="Count", variable.name="Variable", na.rm=TRUE)

# plot and facet by categories
library(ggplot2)
qplot( data=mydf.molten, x = Variable, y = Count, geom="bar", stat = "identity" ) + facet_wrap( "Category" )

enter image description here

For further details, I'd recommend to consult the ggplot2 manual, especially the chapter about geom_bar and facet_wrap.

like image 23
Beasterfield Avatar answered Nov 06 '22 21:11

Beasterfield