0

I'm looking to plot geospatial data in R.

I have a data frame that has Lon, lat and activity as columns. Simplified, it looks something like

structure(list(lon = c(-0.198418, -0.19847, -0.198493, -0.198261, 
-0.198308, -0.19826), lat = c(51.565559, 51.565564, 51.565588, 
51.565695, 51.565524, 51.565492), ride = c(10L, 10L, 10L, 11L, 
11L, 11L)), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df", 
"tbl", "data.frame"), groups = structure(list(ride = 10:11, .rows = list(
    1:3, 4:6)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", 
"data.frame"), .drop = TRUE))

so something like this, but with several thousand rows per ride:


         lon,      lat, ride
1   -0.19842    51.566  10
2   -0.19847    51.566  10
3   -0.19849    51.566  10
4   -0.19826    51.566  11
5   -0.19831    51.566  11
6   -0.19826    51.565  11

I want to plot the coordinates into routes on a map based on each ride. I have tried using {leaflet}, with the following code

leaflet(data = unnested_rides) %>% 
  addTiles() %>%
  addPolylines(~lon, ~lat)

but it has no way of distinguishing between the grouping variable meaning it is just one long line, and when I include group it crashes RStudio. If possible I'd like to do this in {leaflet} as it doesn't require a Google API, but would be open to using {ggmaps} if it was significantly easier / better quality.

My intuition is to iterate over the data, adding the grouped data in layers, although I'm not really sure how to go about this. Does anyone have any suggestions? The data has been downloaded from Strava, if that's of any interest to anyone.

Thanks!

1 Answers1

0
  • If you need static map, I suggest to move into a static-map package. If you're most comfortable with plot() syntax, start with this kind of tuto which show you how to renders several groups of roads. If you're most comfortable with ggplot() syntax, start whith this kind of tuto. Both give you an easy control on the road layers (left you with the permanent quest to find the better data-source for your needs). Both let you produce static map (or several static map in a .gif or a video).

  • I guess your computer crash because leaflet don't need your data, you need to indicate your data for the lines after, in the addPolylines(data = mydf2, lng = ~long, lat = ~lat, group = ~group). See this answer in SO.

PS: There are many technologies to display maps, and then, there are many options to represent the information visually. Since you're looking for 'plot geospatial data' and leaflet syntax is very specific to plot the dynamic layers of a map and nor to produce static images, you should consider to (a) load the leaflet map, then (b) add polylines or some point (markers), in order to indicate the road on a map where there is (the road don't render in another colour). https://rstudio.github.io/leaflet/markers.html.

Clément LVD
  • 466
  • 4
  • 11