user2800105 user2800105 - 3 months ago 36
R Question

Create histogram of raster in R

I want to create a value distribution chart, like a histogram or graph, of a raster image using:

library(raster)
library(sp)
library(rgdal)
DEM <- raster("NR.tif")
hist(DEM)
plot(DEM)


plot()
is used to validate my data and shows me an all green image. Supposedly band 1 of 3.
However I can't see other bands?
Obviously the distribution in the histogram doesn't represent interpolated values in the imagefile.
A histogram created in ARCgis is herehist, which I believe represent the true values.

Any suggestions on how to create a histogram of the real values like the image.

Best,
Mathias

Answer

You could try

download.file("https://www.dropbox.com/s/t279m5ojners7fl/NR.tif?dl=1", 
              tf <- tempfile(fileext = ".tif"), mode="wb")
library(raster)
library(tiff)
library(ggplot2)
library(reshape2)
DEM <- readTIFF(tf)
plot(as.raster(DEM))

enter image description here

ggplot(melt(DEM), 
       aes(value, fill=as.factor(Var3))) + 
  geom_histogram(position="dodge") 

enter image description here


Or, with regards to your update

r <- as.raster(DEM)
tab <- as.data.frame(sort(table(r)))
ggplot(subset(tab, !r %in% c("#F0F0F0", "#000000")), 
              aes(x=r, y=Freq, fill=I(r))) + 
         geom_bar(stat="identity") + 
  theme(axis.text.x = element_text(angle=90))

enter image description here