Search code examples
rerror-handlingbar-chartcol

How to create a side by side barplot in R? (Error in -0.01 * height : non-numeric argument to binary operator)


I have a matrix of type

    1    2    3    4    5   
A " 9" "27" " 0" "46" "50"
B "46" "34" "27" "22" " 3"

which I am trying to create a barplot of with

barplot(df, beside=TRUE)

but I am getting an error message

Error in -0.01 * height : non-numeric argument to binary operator

and I don't what is going wrong. I want the barplot to be a side by side barplot that goes from 1-5 like the column names and there's two bars (A and B) for each number side by side.


Solution

  • Your numbers are stored as characters, that's why you get the non-numeric argument error. Try this:

    df <- matrix(c("1","2","3","4"), ncol = 2) #use your own data, just to make it reproducible
    
    df <- apply(df,1, as.numeric)
    
    barplot(df, beside=TRUE)