Barry
Barry

Reputation: 739

how to rescale the Y axis (frequency) of a histogram in R?

I have this raster file and I want to rescale the y axis (frequency) to [0,1](by dividing the frequency by the sum of all frequencies).

conne <- file("C:\\fined.bin","rb")
sd<- readBin(conne, numeric(), size=4,  n=1440*720, signed=TRUE)
y<-t(matrix((data=sd), ncol=1440, nrow=720))
r = raster(y)
hist(r, breaks=30, main="SMD_2010",
        xlab="Pearson correlation", ylab="Frequency", xlim=c(-1,1))

example:


        values  frequency        (rescaled by dividing each frequency by the sum(85600))
          -1    0                       0
        -0.5    100               0.001168224
           0    38000                 0.443925234
         0.5    7500                  0.087616822
        0.75    40000                 0.46728972

enter image description here

Upvotes: 3

Views: 7268

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98419

One solution is to save the histogram os object. If you look on structure of this object you can see that heights of histogram bars are stored in element counts.

r<-sample(1:25000,1000)
hist.ob <- hist(r)
str(hist.ob)
List of 7
 $ breaks     : num [1:14] 0 2000 4000 6000 8000 10000 12000 14000 16000 18000 ...
 $ counts     : int [1:13] 75 46 72 91 71 91 74 87 86 82 ...
 $ intensities: num [1:13] 3.75e-05 2.30e-05 3.60e-05 4.55e-05 3.55e-05 4.55e-05 3.70e-05 4.35e-05 4.30e-05 4.10e-05 ...
 $ density    : num [1:13] 3.75e-05 2.30e-05 3.60e-05 4.55e-05 3.55e-05 4.55e-05 3.70e-05 4.35e-05 4.30e-05 4.10e-05 ...
 $ mids       : num [1:13] 1000 3000 5000 7000 9000 11000 13000 15000 17000 19000 ...
 $ xname      : chr "r"
 $ equidist   : logi TRUE
 - attr(*, "class")= chr "histogram"

To transform your data so that sum of all bar heights will be 1, you have to divide the each number with the sum of counts number. Then use plot() function to get the new plot.

hist.ob$counts<-hist.ob$counts/sum(hist.ob$counts)
plot(hist.ob)

Upvotes: 2

Related Questions