wfbarksdale
wfbarksdale

Reputation: 7606

How do I plot the densities from a histogram?

So I want to do something like this in R:

 x <- rnorm(1000, 100, 50)
 h <- hist(x, breaks="fd")
 z <- plot(h$breaks, h$density)

The problem is that the $breaks field in the histogram has one more value than the $density field? is there an easy way around this problem?

Upvotes: 0

Views: 362

Answers (2)

wfbarksdale
wfbarksdale

Reputation: 7606

Turns out all I needed to do was to set the freq field to FALSE

So I just did hist(rnorm(1000, 100, 50), freq="FALSE") and that did a histogram of relative frequencies.

Upvotes: 1

joran
joran

Reputation: 173737

I'm not sure exactly what the problem is, but you could just drop either the first or last element of h$breaks to plot the points at either endpoint, or you could drop the last element and then add half the bin width to plot them at the midpoints:

plot(h$breaks[-length(h$breaks)] + 5, h$density)

That just fixes your specific problem, though. There may be a better way of using hist in general, if you expanded on what you're trying to do a bit.

Upvotes: 0

Related Questions