Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add density lines to histogram and cumulative histogram

I want to add density curve to histogram and cumulative histogram, like this:

enter image description here

Here is as far I can go:

hist.cum <- function(x, plot=TRUE, ...){
  h <- hist(x, plot=FALSE, ...)
  h$counts <- cumsum(h$counts)
  h$density <- cumsum(h$density)
  h$itensities <- cumsum(h$itensities)
  if(plot)
    plot(h)
  h
}
 x <- rnorm(100, 15, 5)
hist.cum(x)
 hist(x, add=TRUE, col="lightseagreen")

 #
lines (density(x), add = TRUE, col="red")
like image 591
jon Avatar asked Dec 19 '12 20:12

jon


People also ask

How do you add density to a histogram?

A basic histogram can be created with the hist function. In order to add a normal curve or the density line you will need to create a density histogram setting prob = TRUE as argument.

What is a density line in a histogram?

Description. As known as Kernel Density Plots, Density Trace Graph. A Density Plot visualises the distribution of data over a continuous interval or time period. This chart is a variation of a Histogram that uses kernel smoothing to plot values, allowing for smoother distributions by smoothing out the noise.

Can histograms show distribution density?

Superimposing a DensityA histogram can be used to compare the data distribution to a theoretical model, such as a normal distribution. This requires using a density scale for the vertical axis.


1 Answers

Offered without explanation:

## Make some sample data
x <- sample(0:30, 200, replace=T, prob=15 - abs(15 - 0:30))

## Calculate and plot the two histograms
hcum <- h <- hist(x, plot=FALSE)
hcum$counts <- cumsum(hcum$counts)
plot(hcum, main="")
plot(h, add=T, col="grey")

## Plot the density and cumulative density
d <- density(x)
lines(x = d$x, y = d$y * length(x) * diff(h$breaks)[1], lwd = 2)
lines(x = d$x, y = cumsum(d$y)/max(cumsum(d$y)) * length(x), lwd = 2)

enter image description here

like image 98
Josh O'Brien Avatar answered Sep 19 '22 01:09

Josh O'Brien