2

I am new to R and sorry for this simple question.I would like to calculate the percentage frequency distribution of h1 and h2. How can I combine h1 and h2 in one plot? I tried the following code.

    h1=c(5.18,4.61,3.30,7.58,3.00,3.80,1.95,2.67,2.77,2.73,2.33,3.36,3.50,1.91,4.25,3.87,2.86,2.26,2.00,3.86,3.33,3.59,4.00)
h2=c(2.1,2.1,2.6,2,3.6,2,2.7,1.8,3.1,3.9,3.8,2.6,1.9,2.6,2.1,3.9,2.7,1.8,2.1,2.3,2.2,2.6,1.8,2.3,2.3,3.7,3.3,1.9,2.4,2.6,2.4,3.4,2.4,2.2,1.8,2.1,2,1.2,3.9,1.9,3.4,2,2.2,2.3,2.6,2,3,1.8,1.6,1.5,2.6,3.2,2.3)
h = hist(h1)
h$density = h$counts/sum(h$counts)*100
plot(h, freq=F, ylab='Percentage') 
ayya
  • 31
  • 1
  • 4
  • Check if this link helps http://stackoverflow.com/questions/3541713/how-to-plot-two-histograms-together-in-r – akrun Mar 09 '15 at 12:40

1 Answers1

0

using your data try something like this

first define the xlimits of the plot and the breakpoints for the histogram

    xLimits <- range(c(h1, h2))
    breakPoints <- seq(xLimits[1], xLimits[2], length.out = 20)

now calculate the histograms as you were doing before

    hist1 <- hist(h1, breaks = breakPoints, plot = F)
    hist1Percentage = hist1$counts/sum(hist1$counts)*100

    hist2 <- hist(h2, breaks = breakPoints, plot = F)
    hist2Percentage = hist2$counts/sum(hist2$counts)*100

finally plot them on the same plot

    barplot(hist1Percentage, col = "#ff000050")
    barplot(hist2Percentage, col = "#0000ff50", add = T)

you can also look at a little blog post i did on this.

http://www.rmnppt.com/repeatedDistributions.html

i hope it helps :-)

roman
  • 1,340
  • 9
  • 33