0

I am using the following code to get grouped barplot using R barplot function.

> df <- read.csv2(text = "x;y;z
  A;40;11
  B;66;16
  C;27;13
  D;10;42")
> bp <- barplot(t(df[ , -1]), beside=T, names=df$x)

but this is not working when my data has decimals. Like I can't get a barplot if my data is like:

> df <- read.csv2(text = "x;y;z
  A;40.9;11
  B;66;16
  C;27;13
  D;10;42")

Is there a way to modify this code to get plots for the decimal values as well? I want to use R barplot function, rather than going into some R package.

Thank you

2
  • 1
    make sure that the columns you transpose are numeric. in your example, y is a character, so if you fix that, it should work Commented Jan 18, 2021 at 6:03
  • I didn't get it. Would you please elaborate a little? Thank you. Commented Jan 18, 2021 at 17:56

2 Answers 2

1

Use a comma rather than a dot in your df:

> df <- read.csv2(text = "x;y;z
  A;40,9;11
  B;66;16
  C;27;13
  D;10;42")
Sign up to request clarification or add additional context in comments.

Comments

0

You can use type.convert to convert the character type of data to numeric.

barplot(type.convert(t(df[-1])), beside = TRUE, names=df$x)

enter image description here

2 Comments

Thank you so much, it worked. However, the fill option is not working to define color of the bars, with this method. Is there any solution to it?
You can specify color using col argument. Try barplot(type.convert(t(df[-1])), beside = TRUE, names=df$x, col = c('red', 'green'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.