cassisbonbon
cassisbonbon

Reputation: 23

How to plot a barchart or histogram in R, indicating the probability (discrete data)?

I am new to R. I have discrete data. I want to plot a chart (barchart or histogram) indicating for each existing value (in my data) the normalized number of occurrences (actual count for that value divided by total records). For the moment I have figured out to use:

hist(mydata$x,5,probability = TRUE)

where the number 5 corresponds to the number of rectangles. This example works if the base of the rectangle is length=1, therefore I would always need to know the range of results and I could not have data like {0, 0.5, 1, 1.5, ...}. How to make a more general solution? I really think that there is a single line solution, for something so basic. Thanks

Upvotes: 0

Views: 4655

Answers (2)

labros labrou
labros labrou

Reputation: 1

Yes. There is a line for this.

barplot(prop.table(table(data$x))) data$x is a discrete variable. table(data$x) will give you a table with the first row=the different values of data$x and the second row=the frequencies of each of those values. prop.table(table(data$x)) will also give you a table. The same table but this time each value will be divided by the length of the variable data$x so you will get the probability of having each different value. barplot will plot you a barchart. At x-axis you will get the first row of prop.table(table(data$x)). And at y-axis you will get the second row of prop.table(table(data$x)).

Upvotes: 0

holgrich
holgrich

Reputation: 361

I assume your are looking for the combination

table()
barplot()

e.g.

counts <- table(mtcars$gear)
barplot(counts / sum(counts), main="Car Distribution", xlab="Number of Gears") 

Upvotes: 1

Related Questions