So basically I have some spatial data, which I've found weighted matrix by distance dnearneigh in R and I am wondering if I can generate an interactive plot of the link distribution by changing the distance variable for the weighted matrix.
The data set:
CA.poly <- readShapePoly('CaliforniaCounty.shp')
This is a shapefile for California county and using this I can generate a weight matrix based on the distance of each county.
coords<-coordinates(CA.poly)
W_dist<-dnearneigh(coords,0,1.5,longlat = FALSE)
And after generating the matrix I can plot the link distribution by using:
plot(W_dist,coordinates(CA.poly))
This will show a network of counties where two counties are connected if their distance (between centroids) are less than 1.5 km.
All the codes are in a Rmd file and I am wondering is there a way to output in html an interactive plot where you (user) can change the distance parameter (change 1.5 km to 1 km for example) and the graph will change.
I looked up methods like using shiny and plotly but I don't think they suit my goal. Any suggestions?
Related
I generate a raster map in R with some shaded portion, then i plot my shape file on the raster file to show boundaries of the map. I can calculate the the overall shaded area with a code but I want to calculate the shaded region coming under the separate polygons when i plot shape file on raster. Please help me with the code.
I am using maxent in R to have an idea of suitable area of certain crop for whole country. when I generate map, it is a raster file and I can calculate suitable area for whole country with a code, but I want to calculate the area for provinces as well for which i plot province vise shape file on the raster map.
I want help with the area calculation for each shaded polygon when i plot shape file on raster
pred_me2 [pred_me2 <=0.33] <- NA
pred_me2 [pred_me2 >0.66] <- NA
cell_size<-area (pred_me2, na.rm=TRUE, weights=FALSE)
cell_size<-cell_size[!is.na (cell_size)]
suitable<-length (cell_size)*median(cell_size)
You can try with this:
cell_size <- xres(pred_me2)*yres(pred_me2)
area_NA<- sum(is.na(values(pred_me2))) * cell_size
area_non_NA <- sum(!is.na(values(pred_me2))) * cell_size
I am trying to produce raster plots of whole world with bioclimatic variables from Chelsa or WorldClim.
I am not able to produce nice maps especially while working with precipitation data having large range of values. Trying any colour scale lead to almost mono colour maps because of just few spots with very high precipitation and the rest of world with relatively low.
Is there some elegant way how to stretch the colours while plotting maps? I prefer nonlinear stretch using log or standart deviation. Is there any way without need of compute and save completely new raster?
I have tried function form raster package stretch but my PC was not able to allocate data during run of function into PC memory.
For map composing, you don't need to create a new raster, just change legend color range.
library(raster)
library(classInt)
library(rasterVis)
library(RColorBrewer)
r <-getData('worldclim', var='bio', res=10)
levelplot(r[[12]], col.regions=colorRampPalette(brewer.pal(9, 'Blues')),margin=FALSE,main ='Normal breaks')
Using classIntervals() function from classInt package, you can compute new breaks.
breaks <- classIntervals(r[[12]][!is.na(r[[12]])], n = 50, style = "quantile")
levelplot(r[[12]], at = breaks$brks, col.regions=colorRampPalette(brewer.pal(9, 'Blues')),margin=FALSE,main ='Quantile breaks')
I am working with dataframe which has lat and long coordinates. I want to cluster those coordinates based on their location closeness in R and then plot it on some map.
I am able to plot the points on map with leaflet package,which gives me nice map layout and lat and long coordinates. Just don't know how to cluster those points lets say in 3 clusters. Will k-means clustering appropriate for this kind of problems? Or do I have to apply some distance metrics and then use clustering algorithm. I am bit confused with online literature available on clustering of geographic data.
Here is what I am doing in R
map <- leaflet() %>%
addTiles() %>% # Add default OpenStreetMap map tiles
addMarkers(lng=df_final$order_long, lat=df_final$order_lat)
map
Please help.
Can you help clarify your question: Do you already know the lon/lat coordinates about which you would like to cluster your data or are you trying to determine the ideal centroids based on your data?
If you know the coordinates of each centroid, then you could just run your data through the kmeans algorithm with a max iteration of one. The following would do that:
set.seed(1)
centroids <- data.frame(lat=1:3, lon=4:6) # Input the coordinates for your centroids here
locations <- data.frame(lat=runif(50,1,3), lon=runif(50,4,6))
kmeans(locations, centroids, iter.max=1) # Set your initial centroids and then iter once
If you do not know the coordinates and want kmeans to find them for you, then just increase iter.max or leave it as default (10).
This question has been asked several times here, please use search.
k-means is a bad choice for such data:
how do you find k?
k-means uses squared-Euclidean but you want a spherical geo-distance
k-means is sensitive to outliers
If you google a little bit, you will find examples why this does not work well. Instead, have a look at OPTICS for example.
I would like to be able to create an elevation plot from contour lines in R. I am very new to using shape files
At the moment I have downloaded data from here
which provides .shp files for all of the UK.
It also provides the contour lines, summarising the topology of the UK.
For the elevation plot I would like a data.frame or data.table of evenly spaced points (100m apart from each other) to produce a data output giving an x, y and z value. Where x and y represent the latitude and longitude (or Eastings and Northings), and z represent the height (in meters above sea-level).
I think there are probably some tools that will automatically carry out the interpolation for you, but am unsure how it would work with geo-spatial data.
This is my basic start...
require(maptools)
xx <- readShapeSpatial("HP40_line.shp")
Choose "ASCII Grid and GML (Grid)" as download format for the "OS Terrain 50" product, and download the file. This will give you a zip file containing many directories of zip files, each of which contains portions of a 50 m elevation grid of the UK (the portion I looked at had 200 x 200 cells, meaning 10 km x 10 km). I went into the directory data/su, unzipped the zip file there, and did
library(raster)
r = raster("SU99.asc")
plot(r)
to aggregate this to a 100 m grid, I did
r100 = aggregate(r) # default is factor 2: 50 -> 100 m
As mentioned above, the advice is to work on the grids as contour lines are derived from grids, working the other way around is a painful and a great loss of information.
Getting grid values in longitude latitude as a data.frame can be done in two ways:
df = as.data.frame(projectRaster(r, crs = CRS("+proj=longlat")), xy = TRUE)
unprojects the grid to a new grid in longitude / latitude. As these grids cannot coincide, it minimally moves points (see ?projectRaster).
The second option is to convert the grid to points, and unproject these to longitude latitude, by
df2 = as.data.frame(spTransform(as(r, "SpatialPointsDataFrame"), CRS("+proj=longlat")))
This does not move points, and as a consequence does not result in a grid.
I want to plot a heatmap on a ggmap.
library(ggmap)
turku<-get_map('turku', zoom=13)
turkumap<-ggmap(turku, extent="device", legend="topleft")
turkumap
turkumap+geom_density2d(mapping=aes(x = lon, y = lat),data = test, )
We have made a measurement campaign, so I have 4460 geo-referentiated points.
To have a prediction map, I created a grid 400*400, for a total of 160000 points in which I calculate the prediction with kriging.
To have a full picture of the phenomenon in my 3 km *3 km i think some kind of heat map is necassary because plotting only the points, if I am not
doing anything wrong plots a filled square on the map. (See file)
The code I use to plot the points is:
turkumap <- turkumap + geom_point(data=temp, aes(x=lon, y=lat),size=var1.pred)
So basically the problem is that the points are along roads, so a heat map is problematic
(see here) and there are too many to plot them singularly.
Any suggestions?
The other related question is that my data are in the classical format of gstat, SpatialPointsDataFrame, this means that I have to coerce them to be dataframes to use
ggplot, is there a better practice?
The link provided by #SlowLearner solved my issue