rrgraph

How can i barplot a dataframe contains character an numeric in R?


I have this data frame

product Total
AF064   21
AF065   24
AF066   1
AF067   13
AF068   6
AF069   3
AF070   5
AF071   1
AF072   3
AF073   3
AF074   5
AF075   2
AF076   28
AF077   0
AF078   3
AF079   10
AF080   0
AF081   13
AF082   0
AF083   3
AF084   3
AF085   2
AF086   3
AF087   0
AF088   1
AF089   1
AF090   2
AF091   4
AF092   2
AF093   3
AF094   2
AF095   3
AF096   1
AF097   2
AF098   2
AF099   1
AF100   21
AF101   1
AF102   3

I want to make barplots from this dataframe.

My code is

barplot(product,Total)
**Error in -0.01 * height : non-numeric argument to binary operator**

I also tried

barplot(dataframe)
**Error in barplot.default(dataframe) : 
  'height' must be a vector or a matrix**

I've also tried as.character for the product but still can't do the graph. I really appreciate your help guys, much thanks.


Solution

  • Your first attempt was almost right,

    attach(dataframe)
    barplot(Total,names.arg=product)
    

    would do it.

    Another possibility, is to turn the df into a matrix and feed it to the barplot() function.

    The barplot() function will draw a bar for each column of the matrix, so you need to transpose the immediate conversion of the dataframe

    m <- t( matrix(dataframe[,2],dimnames=dataframe[1]) )
    barplot(m)
    

    In case you have multiple columns (e.g. 2 to 3) in your data frame you can put all of them in the matrix, as rows:

    m <- t(as.matrix(dataframe[,2:3]))
    colnames(m) <- dataframe[,1]
    barplot(m,legend=T)
    

    As for your last comment, you could turn the labels sideways and resize them a little bit. I.e. using directly the dataframe

     attach(dataframe)
     barplot(Total,names.arg=product,cex.names=0.6,las=2)
    

    or using the matrix m

     barplot(m,cex.names=0.6,las=2)