Reputation: 146
I am using R to display some polygons on a map. Polygons are stored in a geoJson file and there are many of them (around 1000). In some geojson files may be even much more.
Here is the R program reading the geojson file and drawing polygons on a map:
library ("ggplot2")
library ("sf")
library ("rnaturalearth")
library ("rnaturalearthdata")
library ("ggspatial")
library ("geojsonR")
europe <- ne_countries (continent = "europe", scale = "medium", returnclass = "sf")
class (europe)
p <- ggplot (data = europe)
p <- p + geom_sf ()
js <- FROM_GeoJson (url_file_string = "file.geojson")
i <- 0
for (f in js$features) {
if (!is.null (f$properties$InterferenceLevel)) {
if (i < 250) {
#print (f$properties$InterferenceLevel)
#print (f$geometry$coordinates)
overlay_polygon <- f$geometry$coordinates
overlay_polygon <- sf::st_polygon (list(f$geometry$coordinates))
#print (overlay_polygon)
poly <- sf::st_as_sfc (list (overlay_polygon), crs = 4326)
p <- p + geom_sf (data = poly, fill=alpha ("red", 0.2), color=alpha ("red", 0.2))
}
i <- i + 1
#print (i)
}
}
p <- p + coord_sf(xlim = c(-20, 42), ylim = c(35, 72))
plot (p)
The problem I have is that if I want to draw all polygons in that way, the program stops and reports
Error: C stack usage 7970756 is too close to the limit
I have added another condition involving a counter to see how many polygons I can draw. At 250 the map is shown. If I go higher, I get the error message.
Does anybody has an idea of another way to draw transparent polygons over the map in a way that does not fill up the stack size? I do not have much experience with ggplot. I have been using charts with tens of thousands of dots without problems and here I cannot draw more than a couple of hundreds polygons. I am sure there is a way to do it. I just don't know how to add them to the map once it is shown in a window. It does not have to be ggplot if it can be done with some other function.
Upvotes: 0
Views: 51
Reputation: 94182
Its not sf
as such, you can't have so many items in a ggplot
. This loop adds a single data point using geom_point
and prints a counter until it falls over:
p = ggplot()
i = 1
while(TRUE){
p = p + geom_point(data=data.frame(x=runif(1),y=runif(1)),aes(x=x,y=y))
message(i);i=i+1
}
For me this runs until 878 and then I get Error: C stack usage 7974740 is too close to the limit
Solution is to amass your data into a single data frame and add it with one geom_
call.
If you need to colour or style them in some way, keep that in the data frame too, and specify that attribute not as an aes()
but as a vector parameter, eg:
geom_sf(all_my_polys, col=all_my_polys$colour)
Upvotes: 4