neversaint
neversaint

Reputation: 64064

How to Plot Density from Frequency Table

Given a frequency table below:

> print(dat)
V1    V2
1  1 11613
2  2  6517
3  3  2442
4  4   687
5  5   159
6  6    29

# V1 = Score
# V2 = Frequency

How can we plot the density, (i.e. y-axis range from 0 to 1.0).

Currently the I have the following for frequency plot:

plot(0,main="table",type="n");
lines(dat,lty=1)

# I need to use lines() and plot() here, 
# because need to make multiple lines in single plot

Not sure how to approach that for density.

Upvotes: 3

Views: 3779

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174928

The density of each block would be V2 / sum(V2) assuming that each row is a separate block.

For your data

dat <- data.frame(V1 = 1:6, V2 = c(11613, 6517, 2442, 687, 159, 29))

I get:

> with(dat, V2 / sum(V2))
[1] 0.541474332 0.303865342 0.113862079 0.032032452 0.007413624 0.001352170

Which we can check using R's tools. First expand your compact frequency table

dat2 <- unlist(apply(dat, 1, function(x) rep(x[1], x[2])))

Then use hist() to compute the values we want

dens <- hist(dat2, breaks = c(0:6), plot = FALSE)

Look at the resulting object:

> str(dens)
List of 7
 $ breaks     : int [1:7] 0 1 2 3 4 5 6
 $ counts     : int [1:6] 11613 6517 2442 687 159 29
 $ intensities: num [1:6] 0.54147 0.30387 0.11386 0.03203 0.00741 ...
 $ density    : num [1:6] 0.54147 0.30387 0.11386 0.03203 0.00741 ...
     $ mids       : num [1:6] 0.5 1.5 2.5 3.5 4.5 5.5
 $ xname      : chr "dat2"
 $ equidist   : logi TRUE
 - attr(*, "class")= chr "histogram"

Note the density component which is:

> dens$density
[1] 0.541474332 0.303865342 0.113862079 0.032032452 0.007413624 0.001352170

Which concurs with my by-hand calculation from the original frequency table representation.

As for the plotting, if you just want to draw densities instead then try:

dat <- transform(dat, density = V2 / sum(V2))
plot(density ~ V1, data = dat, type = "n")
lines(density ~ V1, data = dat, col = "red")

If you want to force axis limits do:

plot(density ~ V1, data = dat, type = "n", ylim = c(0,1))
lines(density ~ V1, data = dat, col = "red")

Upvotes: 4

Related Questions