3

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

Barry
  • 739
  • 1
  • 8
  • 29

1 Answers1

2

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)
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • 1
    @Barry Dividing by sum() will change the range. So the dividing by maximal value will keep range 0-1. If this not the solution you need then please update your question to explain more what you mean by scale y axis. – Didzis Elferts Feb 01 '13 at 16:59
  • @Barry - checked with your sample data - if you use sum(hist.ob$counts), then the total sum of heights will be 1. In my sample data all values were quite similar so you saw so small values after transformation. – Didzis Elferts Feb 01 '13 at 17:46
  • Here's a [solution](https://stackoverflow.com/questions/7324683/use-hist-function-in-r-to-get-percentages-as-opposed-to-raw-frequencies) that retains the y-axis. – Rithwik Aug 20 '22 at 19:45