J_p
J_p

Reputation: 475

Barplot with factors error?

How to plot a barplot with a column that contains factors? i did this with the cars93 dataframe that is in R.

library(MASS)
barplot(Cars93$Type)

and gives this:

 'height' must be a vector or a matrix

Why isn't this working?

Upvotes: 2

Views: 2416

Answers (3)

zx8754
zx8754

Reputation: 56004

Use plot instead of barplot:

plot(Cars93$Type)

As class of x is factor plot will call plot.factor, and when y is missing barplot is produced.

> class(Cars93$Type)
[1] "factor"

See ?plot.factor for more info.

Upvotes: 0

drmariod
drmariod

Reputation: 11762

Or you can use the dataset directly via ggplot2

library(ggplot2)
ggplot(Cars93, aes(Type)) + geom_bar()

Upvotes: 1

gsa
gsa

Reputation: 800

You can achieve this like that:

barplot(table(Cars93$Type))

Upvotes: 3

Related Questions