Create histogram of raster in R - 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

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))
ggplot(melt(DEM),
aes(value, fill=as.factor(Var3))) +
geom_histogram(position="dodge")
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))

Try setting the NAvalue to the background color and then call the hist() function or use the ggplot commands from lukeA:
library(raster)
ras <- stack("Downloads/NR.tif")
NAvalue(ras) <- 240
hist(ras)
This results in the following plots:

Related

ggplot2 overwrites plot limits

I have two shapefiles, which I would like to plot into a given plot extent. One of the shapefiles exceeds the extent and when plotted it automatically overwrites the limits of the extent. This happens when loading the shapefiles using the terra package and plotting it using the tidyterra functions, but it is not an issue when reading the shapefiles using the old readOGR function and ploting it using the core ggplot2 functions.
# libraries
library(terra)
library(tidyterra)
library(ggplot2)
library(ggspatial)
library(raster)
library(sp)
library(sf)
library(rgdal)
EXAMPLE 1 - I don't want this
# read shapefiles
SHP1 <- terra::vect('file1.shp')
SHP2 <- terra::vect('file2.shp')
# plot
ggplot() +
coord_equal(ylim=c(100000,800000)) +
geom_spatvector(data=SHP1,fill=NA,color='grey',inherit.aes=T) +
geom_spatvector(data=SHP2,fill=NA,color='green',size=1)
EXAMPLE 2 - I want this
# read shapefiles
SHP1 <- terra::vect('file1.shp')
SHP2 <- terra::vect('file2.shp')
ggplot() +
coord_equal(ylim=c(100000,800000)) +
geom_polygon(SHP1,mapping=aes(x=long,y=lat,group=group),fill=NA,color='grey',size=0.1) +
geom_polygon(SHP2,mapping=aes(x=long,y=lat,group=group),fill=NA,color='green',size=0.5)
How could I obtain map from example 2 using the geom_spatvector function used in example 1?
I really would like to use the terra package to read and manipulate shapefiles but then it produces SpatVector class object which is not supperted by the ggplot2 function. This means that only for the plotting purposes I have to transfer it to the older SpatialPolygonsDataFrame and this is exactly what I would like to avoid.
You need to use coord_sf rather than coord_equal. Obviously, we don't have your shapefile, but if I take a similar shapefile of Germany, then we can demonstrate:
library(tidyterra)
library(ggplot2)
p <- ggplot(SHP1) +
geom_spatvector()
Firstly, with the standard geom_spatvector plot:
p
Secondly, with axis limits written by a call to geom_sf:
p + coord_sf(ylim = c(47, 52))

Draw boundaries using groups and order for each region gg_map Rgooglemaps

I'm trying to plot custom boundaries (dma's) into a google map.
library(ggmap)
library(ggplot2)
US <- get_map(location = c(-95.7129,37.0902),zoom = 3)
US_map <- ggmap(US)
then using the following CSV file with the coordinates groups and order
https://www.dropbox.com/s/3xv192k5401np4r/DMAs%20coordinates%20sample.csv?dl=0
Then I can plot the coordinates using dots:
smpl <- read.csv('DMAs coordinates sample.csv')
US_map + geom_point(data=smpl,aes(x=Longitude, y=Latitude),size=0.01)
But I would like to plot lines connected by these dots using the path from point_order and group each set of lines using dma_boundary.UniqueID I'm sure there's a way to do this. but I cannot find the right way.
I found a way to do this,
Using geom_path for each group represented by dma_boundaty.UniqueID
As the data is already sorted by sub_polygon_id and point_order we use geom_path to use the order set in data. Then,
library(ggplot2)
library(data.table)
library(ggmap)
dma_boundaty <- data.table(read.csv('.../path')
US <- get_map(location = c(-95.7129,37.0902),zoom = 3)
US_map <- ggmap(US)
dma_map <- US_map + lapply(0:205,function(i) {
geom_path(data=dma_boundary[dma_boundary.UniqueID == i,],aes(x=Longitude, y=Latitude))})

R Plotly - Scatter plot: Colouring individual points

I am trying to specify the color of the points in my scatter plot. I would like to be able to specify a different color and alpha for each point.
The following snippet gives me the error "Error in grDevices::col2rgb(colors, alpha = alpha) :
invalid color name 'rgba(105,100,30,.6)'"
I am quite stuck on this, any help is appreciated.
Thanks!
library(plotly)
library(ggplot2)
library(igraph)
tree <- make_tree(127,2)
tree_layout <- layout_as_tree(tree)
tree_layout_df <- as.data.frame(tree_layout)
Xn <- tree_layout_df[,1]
Yn <- tree_layout_df[,2]
marker_color <- rep('rgba(105,100,30,.6)',127)
reg_tree_plot <- plot_ly() %>%
add_trace(x=~Xn, y=~Yn, type='scatter', mode='markers',color=~Xn,
colors=marker_color)
Following definition of marker_color is accepted in grDevices. I used runif and replicate to generate 127 (hopefully) different colours.
marker_color <- replicate(127, rgb(runif(1,0,1),runif(1,0,1),runif(1,0,1),runif(1,0,1)) )

Plot ggplot polygons with holes with geom_polygon

There are questions out there about the fact that ggplot2 can't plot polygon shapes that have holes.
That is because, if the order of points is not OK, the end graph looks bad, usually with clipping/trimming lines inside the donut shape.
I have read a lot about how order matters, but I am not able to step forward.
I have a SpatialPolygonsDataFrame with 26 features (comes from raster::rasterToPolygons(dissolve=T)) and I want to plot it with ggplot.
Here's what happens -
r3.pol <- rasterToPolygons(r3, dissolve=T)
r3.df <- fortify(r3.pol)
names(r3.df) <- c('x','y','order','hole','piece','ID','group')
p <- ggplot(r3.df)
p <- p + geom_polygon(mapping=aes(x=x,y=y,group=ID), fill='red')
p <- p + coord_equal()
I see this output:
While it should be like so, with plot(r3.pol):
How can I make this work?
I tried for hours but I am not able to reorder r3.df.
Also, can the information in r3.df$hole be helpful? It is returned by the function fortify for points that are holes (I think).
Side question: how can I give you my r3.pol SpatialPolygonsDataFrame, so that you can try yourself? I remember seeing long, reproducible "dumps" of objects here, but I don't know how to do it.
I saved the polygons data frame here. Was not able to save it using dput, sorry. You can fetch it using load.
I suggest to install the package "ggpolypath" and use geom_polypath instead of geom_polygon. Works for me.
My temporary solution is: ##$% polygons, and use the raster package.
Namely:
r <- raster(x=extent(r3.pol), crs=crs(r3.pol)) # empty raster from r3.pol
res(r) <- 250 # set a decent resolution (depends on your extent)
r <- setValues(r, 1) # fill r with ones
r <- mask(r, r3.pol) # clip r with the shape polygons
And now plot it as you would do with any raster with ggplot. The rasterVis package might come helpful here, but I'm not using it, so:
rdf <- data.frame(rasterToPoints(r))
p <- ggplot(rdf) + geom_raster(mapping=aes(x=x, y=y), fill='red')
p <- p + coord_equal()
And here it goes.
Alternatively, you can create the raster with rasterize, so the raster will hold the polygons values (in my case, just an integer):
r <- raster(x=extent(r3.pol), crs=crs(r3.pol))
res(r) <- 250
r <- rasterize(r3.pol, r)
rdf <- data.frame(rasterToPoints(r))
p <- ggplot(rdf) + geom_raster(mapping=aes(x=x, y=y, fill=factor(layer)))
p <- p + coord_equal()
If someone comes up with a decent solution for geom_polygon, probably involving re-ordering of the polygons data frame, I'll be glad to consider it.

How to plot additional raster with spplot?

I want to plot SpatialPolygonsDataFrame as a semi-transparent main object (with legend on the right), but I want to plot yet additional raster (hillshade) as a background - just to make nicer map. I would need something like:
spplot(polygons, sp.layout = list(list("raster", myRaster)))
but looking at ?spplot, it doesn't seem to be possible to specify the raster in sp.layout. I can't specify the raster as the main object, because the main object are the polygons dataFrame, whose value scale I want to plot in the legend on the right side.
How is it possible to plot an additional raster in spplot?
Here's one way to do it. There's probably a neater way to achieve it without plotting the polygon object twice, though...
library(sp)
library(rasterVis)
r <- raster(nrow=18, ncol=36)
r[] <- runif(ncell(r)) * 10
r[r > 8] <- NA
pol <- rasterToPolygons(r, function(x) x > 6)
spplot(pol) + levelplot(r) + spplot(pol)
Or alternatively:
library(latticeExtra)
spplot(pol) + spplot(r) + spplot(pol)
EDIT
As per the comment by #OscarPerpiñán, a better way to do this is:
spplot(pol) + as.layer(spplot(r), under = TRUE)

Resources