luukvdmeer / sfnetworks

Tidy Geospatial Networks in R
https://luukvdmeer.github.io/sfnetworks/
Other
334 stars 20 forks source link

Rewrite plot.sfnetwork #228

Closed agila5 closed 1 year ago

agila5 commented 1 year ago

Ref #226. I'm not 100% that this is an exact replica of the old function, but I tested some examples (i.e. the ones documented in the docs) and I get identical results:

library(sfnetworks)
oldpar = par(no.readonly = TRUE)
par(mar = c(1,1,1,1), mfrow = c(1,1))
net = as_sfnetwork(roxel)
plot(net)

# When lines are spatially implicit.
par(mar = c(1,1,1,1), mfrow = c(1,2))
net = as_sfnetwork(roxel, edges_as_lines = FALSE)
plot(net)
plot(net, draw_lines = FALSE)

# Changing default settings.
par(mar = c(1,1,1,1), mfrow = c(1,1))
plot(net, col = 'blue', pch = 18, lwd = 1, cex = 2)

# Add grid and axis
par(mar = c(2.5,2.5,1,1))
plot(net, graticule = TRUE, axes = TRUE)

Created on 2022-09-08 by the reprex package (v2.0.1)

Moreover, it looks like this new approach is quite faster than the current one:

remotes::install_cran("sfnetworks", quiet = TRUE)
library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.2.1, PROJ 7.2.1; sf_use_s2() is TRUE
library(tidygraph)
#> 
#> Attaching package: 'tidygraph'
#> The following object is masked from 'package:stats':
#> 
#>     filter
library(sfnetworks)

set.seed(1)
my_graph <- play_geometry(n = 5000, radius = 0.025)
my_sfn <- as_sfnetwork(my_graph, coords = c("x", "y"))
#> Checking if spatial network structure is valid...
#> Spatial network structure is valid
system.time(plot(my_sfn))

#>    user  system elapsed 
#>   15.79    1.17   17.31

plot_sfnetwork = function(x, draw_lines = TRUE, ...) {
  dots = list(...)
  pch_missing = is.null(dots$pch)
  dots$pch = if (pch_missing) 20 else dots$pch
  nsf = sfnetworks:::pull_node_geom(x)
  do.call(plot, c(list(nsf), dots))
  if (sfnetworks:::has_explicit_edges(x) || draw_lines) {
    x = sfnetworks:::explicitize_edges(x)
    esf = sfnetworks:::pull_edge_geom(x)
    dots$add = TRUE
    do.call(plot, c(list(esf), dots))
  }
  invisible()
}
system.time(plot_sfnetwork(my_sfn))

#>    user  system elapsed 
#>    2.47    1.04    3.55

Created on 2022-09-08 by the reprex package (v2.0.1)

loreabad6 commented 1 year ago

Thank yo uso much @agila5, I had the chance to look into this today and play with larger networks, it si significantly faster and more performant and is certainly reproducing the results correctly. We will include this on the CRAN resubmission we are currently working on 😄

agila5 commented 1 year ago

You're welcome! If you need help with the resubmission let me know.