David M
David M

Reputation: 708

Density plot/histogram using intervals

I have a range of integer intervals, e.g. [1, 5], [1,3], [3,4] for which I would like to create a density plot. I suppose what I really want is a plot of the number of intervals overlapping each integer in the entire range. Using the data above it might looks something like this:

    3     X
    2 X X X X
    1 X X X X X
      1 2 3 4 5

The obvious (and terrible) way I can think of doing it would be to loop through every interval and add all integers to a single vector, then use hist() or a similar function to create my plot. Is there a straightforward way to do this?

Thanks!

Upvotes: 1

Views: 553

Answers (1)

Thomas
Thomas

Reputation: 44525

You seem to be proposing something like this:

x <- list(c(1,5),c(1,3),c(3,4))
hist(unlist(lapply(x,function(z) seq(z[1],z[2]))))          # hist
plot(density(unlist(lapply(x,function(z) seq(z[1],z[2]))))) # density

And yes, this is - as you describe - the obvious solution.

Upvotes: 6

Related Questions