I have > 100 nested polygons in a unique SpatialPolygonsDataFrame
. I desire to plot them with ggplot2
and all of them need to be visible in the map, i.e. overlaying larger polygons have to be in the background.
I found that I can achieve this by using alpha = 0
within the geom_polygon
function but how can I assign a fill colour to each polygon?
Here an example of my code with just 2 polygons:
library(ggplot2)
Read csv file with two shapefiles merged and then converted to data.frame with fortify
from maptools
.
#read csv file shape_1_2.csv
shape_1_2 = read.csv('shape_1_2.csv', stringsAsFactors = FALSE)
#plot
ggplot() +
geom_polygon(data = shape_1_2, aes(x = long, y = lat, group = group),
colour = 'black', size = 1, linetype = 'solid', alpha = 0)
And relative map:
How can I fill with colour these two polygons?
I tried to add fill='black'
in both aes
and geom_polygon
but it doesn't work.
Thanks
Update
I am sorry but I realised that my example data contains NO nested polygons.
So starting from the following data.frame as per https://gis.stackexchange.com/questions/280671/r-create-multipolygon-from-overlapping-polygons-using-sf-package :
shape_df = data.frame(
lon = c(0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 2, 2, 0.8, 1, 1, 2, 2, 1, 1),
lat = c(0, 0, 1, 1.5, 0, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 0, 0, 1, 1, 0),
var = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3 ,3 ,3 ,3 ,3, 4 ,4 ,4, 4, 4)
)
And my plotting code (with alpha=0
):
ggplot() +
geom_polygon(data = shape_df, aes(x = lon, y = lat, group = var),
colour = 'black', size = 1, linetype = 'solid', alpha = 0)
With relative map:
How can I fill the different areas present in the map with one OR up to 4 colours so that the larger polygons remains in the background of the smaller?