0

In R, can I make a histogram of all the non-zero values in my raster?

Some reproducible data below. I just want the histogram to be made with the zeros. Happy with a way to do that, or I guess to create a new raster that just removes all the zero-cells from r.

y=seq(33,34,.1)
coords=expand.grid(x,y)
rdf=data.frame(coords,depth=runif(nrow(coords),0,2))
names(rdf)=c('x','y','value')
r=rasterFromXYZ(rdf)
plot(r)
hist(r)```
2

There isn't an assignment for x in the code above so I can't generate your exact output, but you should be able to plot non-0 entries in your histogram by using hist(r[r!=0]).

Here's an assignment for x (just a placeholder) and some artificially-crafted 0's for the raster values that demonstrate the difference between hist(r) and hist(r[r!=0]):

x = seq(-1,1,.1)
y=seq(33,34,.1)
coords=expand.grid(x,y)
rdf=data.frame(coords,depth=runif(nrow(coords),0,2))
names(rdf)=c('x','y','value')
rdf$value[23:30] = 0 #Added a few 0's to the value column
r=rasterFromXYZ(rdf)
plot(r)
hist(r)
hist(r[r!=0]) # Note reduction in count for lowest bin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.