How to stop fortify from merging overlapping polygons - r

I have a SpatialPolygonsDataFrame containing multiple polygons that I want to plot in ggplot2. However, when I try converting my SpatialPolygonsDataFrame to a dataframe (required by ggplot2) via the fortify {ggplot2} function, polygons that overlap are merged. I know this is where the problem is because View(as.data.frame(data_pre_fortify)) and View(data_post_fortify) tell me the number of polygons before & after fortifying.
Currently my fortify function simply calls fortify(data_post_fortify, region = "id").
Can this merging of polygons be avoided, and if so, how?

Whilst this is by no means a perfect solution, I have managed to work around the issue by creating three SpatialPolygonsDataFrames, each containing only polygons that don't overlap (so overlapping polygons are split between different SpatialPolygonsDataFrames, and then fortifying these on their own. When it came to plotting I therefore had three geom_polygon layers, each calling one of the dataframes containing a subset of polygons.
I realise this isn't a great solution — colour/fill aesthetics cannot be added for all polygons together, plus this manual sorting of overlapping polygons may not be very time effective for larger/more overlapping datasets — so any further answers are very welcome!

Related

Correcting sf great circle ggplots

I am attempting to plot several great circles between points on a world map. I am using sf to generate the great circles, largely following the method outlined here. I am able to generate the plot and lines all ok, except several of the lines wrap around behind the globe so to speak, and I end up with a horizontal line connecting the two points where the great circle paths wrap around - see "Correcting gcIntermediate" here for a visual explanation and a solution for gcIntermediate. Looking at the sf dataframe that has been created, my guess is that I need to split the items where absolute longitude difference is greater than 180 degress into two sf lines. I can kind of see a method that involves many lines of code brute forcing the sf dataframe to resolve this issue, but would very like to see if there are any other better ideas to solve this elegantly.
st_wrap_dateline to the rescue!
path.sf <- st_wrap_dateline(path.sf,
options=c("WRAPDATELINE=YES", "DATELINEOFFSET=180"))
Then plotting this with ggplot2 seems to plot all ok.

Overlapping data contour on a map

I have gone through few tutorials and answers here in stackoverflow such as:
Overlap image plot on a Google Map background in R or
Plotting contours on an irregular grid or Geographical heat map of a custom property in R with ggmap or How to overlay global map on filled contour in R language or https://blog.dominodatalab.com/geographic-visualization-with-rs-ggmaps/
They either don't serve my purpose or consider the density of the data to create the image.
I am looking for a way to plot contour on a map of a certain data, and would expect the image to look something like this:
or something like this taken from https://dsparks.wordpress.com/2012/07/18/mapping-public-opinion-a-tutorial/:
I have a data here that gives a contour plot like this in plot_ly but i want this over the map given by latitudes and longitudes.
Please guide me on how this can be done. Any links to potential answers or codes would be helpful.
Ok I did some digging and figured that to plot the data -which in this case are point values randomly distributed across the Latitude and Longitude, one has to make it continuous instead of the discreetly distributed one. To do this I interpolated the data to fill in the gaps, this method is given in Plotting contours on an irregular grid and then take it from there. Now the interpolation here is done using a linear regression, one can use other methods such as IDW, Kriging, Nearest Neighbourhood etc for which R-packages are easily available. These methods are widely used in climatology and topographic analysis. To read more about interpolation methods see this paper.

Reattach attribute table to Spatial Polygon to make Spatial Polygon Dataframe

I have built a web app using Shiny and Leaflet, but it renders very slowly because the Spatial Polygon DataFrame (merge.proj) that is being added to the map is 20,000 polygons. I may try to allow the user to view only certain neighborhoods at a time as a fix, but first I thought I'd simplify polygons to see how much that sped up the process.
My understanding is that simplifying polygons reduces # of vertices etc and gives you a Spatial Polygon, which loses the attribute table. I was hoping to then reattach the attribute table and re-create a Spatial Polygon Dataframe that is hopefully reduced in size.
However, the code is erroring and all the help I can find online just shows how to do this when making the Spatial Polygon and dataframe from scratch, and I'm having trouble applying what they did to my data (see here). The error says that my polygon IDs and row.names don't match, but they both originally came from the same Spatial Polygon Dataframe so I'm confused. And I'm not sure how to manually manipulate things so they match.
I am pasting below the error and the code I currently have. Any suggestions would be greatly appreciated!
# For faster plotting, simplify polygons
merge.simplify <- gSimplify(merge.proj,0.1,topologyPreserve = T)
# Create a dataframe
merge.df <- data.frame(merge.proj#data)
# Do coercion to SPDF
merge.spdf <- SpatialPolygonsDataFrame(merge.simplify, merge.df)
ERROR: Error in SpatialPolygonsDataFrame(merge.simplify, merge.df) :
row.names of data and Polygons IDs do not match

r gis: find borders between polygons

Having a polygon shapefile, I need to produce a polyline shapefile containing only the common borders between polygons (see the picture).
My question is similar to 1 and 2, only I need to do this in R. The latter similar question refers to a solution with the use of Shapely package for python. The analogue of Shapely for R is rgeos. Though, I couldn't find the solution with rgeos on my own.
Note: the shapefile with borders used for illustration was produced in ArcGIS using the solution from similar question 1. Now I need to do the same in R.
What you want is the lines that are the difference between the set of lines from the dissolved regions and the lines of the regions themselves. IN the rgeos package, gUnaryUnion will dissolve the polygons, and gDifference will subtract.
For my small EU subset eusub, I can do this with:
library(rgeos); library(sp)
borders = gDifference(
as(eusub,"SpatialLines"),
as(gUnaryUnion(eusub),"SpatialLines"),
byid=TRUE)
Note the need to convert polygons to lines because the output will be lines.
Then see this:
plot(eusub)
plot(borders, col="red",lwd=2,add=TRUE)

Sort Extracted Data Based On Image Region

I have analysed tree core images through the raster package in an attempt to perform image analysis. In the image:
http://dx.doi.org/10.6084/m9.figshare.1555854
You can see the measured "vessels" (black and numbered) and also annual lines (red) which have been drawn using the locator function and represent each year of growth of the tree core.
By generating a list of the maximum y coordinates of each annual line I have been able to sort the vessels into years for this image. Which is what I am looking for. However, it has occurred to me that in reality things can get a little more difficult as seen in the next image:
http://figshare.com/articles/Complicated/1555855
The approach above will not work on this image as vessels from each year overrun so using the maximum y coordinates will not return the correct result.
So can anyone suggest another approach which may overcome this limitation? I have thought about using spatialpolygons but not sure this will achieve what I am looking for.
If you are creating the lines by clicking on the plot, you can use raster function drawLine or, for polygons, drawPoly. You could rasterize the polygons and mask that with the original image to get the vessels grouped by polygon (year).

Resources