In 2019 Uber opened up part of its movement data: average speeds per street segment, per hour, for a handful of cities. Berlin was one of them. Joined with OpenStreetMap, it answers a few simple questions. Where do the cars drive, at what time, and how often is the speed limit broken?
This tutorial walks through the whole process in R: loading 2.4 million rows with data.table, joining them to the OpenStreetMap road network with sf, aggregating, plotting with ggplot2, animating with magick, and finally mapping with Leaflet. The interactive charts and maps below are rebuilt from the original outputs.
Context & Objectives
Context
Uber released for some cities the datasets of their drivers movement. Those include the OSM way identifier, the mean and standard speed deviation. In order to anonymize them, the data have been aggregated per hour. Let’s have a look at the Berlin data for the month of June 2019, and how they are distributed in space and time. For this, we will combine those data with the OpenStreetMap shapefile for Berlin.
Objectives
Through this tutorial, we will use some concepts of data analysis :
- handle data formatted as table with the help of the
data.tablepackage, - create some vizualisations with the
ggplot2, - create an animated map with
sfand an interactive one withleaflet.
References
- for
data.table, i found the R Quick Tutorial an excellent introduction. - for
ggplot2, i refer to this - for modeling and data analysis, i kindly refer to The Analytic Edge course, maybe not as fancy as datacamp programs, but free and with a very progressive and accessible learning curve. I personally get into R thanks to this course, the Coursera Stats in R and the
Exploratory_Data_Analysisinteracive console-based course from Swirl.
Getting the data
For this exercise, we will use two datasets, both of them already “cleaned”, it will spare use the long process of data wrangling.
for Uber, just retrieve the data from this link : download
for OpenStreetMap, we use the GeoFabrik website to download the
berlin-latest-free.shp.zipshapefile
Once we are done with those downloads (less than 1GB altogether), we can unzip and store them in the /data folder.
Your /data folder should look like this :

Then we can start with the R code, create a new Notebook,and load the necessary packages with the help of pacman. What pacman does it it checks if the required packages are already installed and if not, install them automatically :
if (!require("pacman")) install.packages("pacman")
pacman::p_load(data.table,
'lubridate',
'ggplot2',
'leaflet',
'sf',
'plotly',
'ggthemes',
'purrr',
'magick',
'plotrix', # For color scales
'classInt')Load the data
Uber data
For Uber, the operation is straightforward, thanks to the fread function from the data.table package. For this exercise, we will use the data.tablepackage to manipulate the data, due to its speed and conciseness compared to the alternative dplyr package.
DT.Uber <- fread('data/movement-speeds-hourly-berlin-2019-6.csv')Once loaded. we can have a glimpse at the Uber table :
str(DT.Uber)## Classes 'data.table' and 'data.frame': 2409465 obs. of 13 variables:
## $ year : int 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 ...
## $ month : int 6 6 6 6 6 6 6 6 6 6 ...
## $ day : int 20 22 2 15 6 30 5 2 10 12 ...
## $ hour : int 18 0 13 0 19 4 19 13 0 9 ...
## $ utc_timestamp : chr "2019-06-20T16:00:00.000Z" "2019-06-21T22:00:00.000Z" "2019-06-02T11:00:00.000Z" "2019-06-14T22:00:00.000Z" ...
## $ segment_id : chr "f50b8a5ca0afcdd31eb48403172284dbc42f2aeb" "f50b8a5ca0afcdd31eb48403172284dbc42f2aeb" "f50b8a5ca0afcdd31eb48403172284dbc42f2aeb" "f50b8a5ca0afcdd31eb48403172284dbc42f2aeb" ...
## $ start_junction_id: chr "dc072f474bcbf30d75bd3b1e42974396af504bbb" "dc072f474bcbf30d75bd3b1e42974396af504bbb" "dc072f474bcbf30d75bd3b1e42974396af504bbb" "dc072f474bcbf30d75bd3b1e42974396af504bbb" ...
## $ end_junction_id : chr "32c9d31816ecf0fde2586bab37995d06ad5f6f3e" "32c9d31816ecf0fde2586bab37995d06ad5f6f3e" "32c9d31816ecf0fde2586bab37995d06ad5f6f3e" "32c9d31816ecf0fde2586bab37995d06ad5f6f3e" ...
## $ osm_way_id : int 30709742 30709742 30709742 30709742 30709742 169753571 169753571 169753571 169753571 169753571 ...
## $ osm_start_node_id:integer64 235637275 235637275 235637275 235637275 235637275 1813307792 1813307792 1813307792 ...
## $ osm_end_node_id :integer64 235637281 235637281 235637281 235637281 235637281 235637281 235637281 235637281 ...
## $ speed_kph_mean : num 48.1 37.3 30.5 39.9 42.9 ...
## $ speed_kph_stddev : num 4.87 8.36 19.27 6.83 4.56 ...
## - attr(*, ".internal.selfref")=<externalptr>Nice gesture from Uber, the utc_timestamp has been also converted to other time dimensions (year,month,day,hour)
As stated on the Uber Movement metadata description, the columns segment_id, start_junction_id,end_junction_id correspond to the deprecated OSM (OpenStreetMap) identifiers for the ways (e.g. street/highways…) and nodes (junctions). Those 3 fields have been replace by the osm_way_id, osm_start_node_id, and osm_end_node_id.
In order to keep the process efficient, we can use our first data.table mutation operation on the table and remove those deprecated columns :
DT.Uber[,c('segment_id', 'start_junction_id','end_junction_id'):=.(NULL,NULL,NULL)]The operation does in fact take place by reference, i.e we do not copy the data.table, but modify it in place, which rquires less memory. We check that the removal operation took place :
str(DT.Uber)## Classes 'data.table' and 'data.frame': 2409465 obs. of 10 variables:
## $ year : int 2019 2019 2019 2019 2019 2019 2019 2019 2019 2019 ...
## $ month : int 6 6 6 6 6 6 6 6 6 6 ...
## $ day : int 20 22 2 15 6 30 5 2 10 12 ...
## $ hour : int 18 0 13 0 19 4 19 13 0 9 ...
## $ utc_timestamp : chr "2019-06-20T16:00:00.000Z" "2019-06-21T22:00:00.000Z" "2019-06-02T11:00:00.000Z" "2019-06-14T22:00:00.000Z" ...
## $ osm_way_id : int 30709742 30709742 30709742 30709742 30709742 169753571 169753571 169753571 169753571 169753571 ...
## $ osm_start_node_id:integer64 235637275 235637275 235637275 235637275 235637275 1813307792 1813307792 1813307792 ...
## $ osm_end_node_id :integer64 235637281 235637281 235637281 235637281 235637281 235637281 235637281 235637281 ...
## $ speed_kph_mean : num 48.1 37.3 30.5 39.9 42.9 ...
## $ speed_kph_stddev : num 4.87 8.36 19.27 6.83 4.56 ...
## - attr(*, ".internal.selfref")=<externalptr>Ok, the three deprecated columns have disappeared.
Now we can have a look at the structure of this table. If we understand correctly the description from Uber, each rows correspond to the aggregation of n trips per hour slot perosm_way_id (e.g. a part of the street), and per origin and destination (osm_start_node_id & osm_end_node_id).
Let’s take a sample of the table :
DT.Uber[osm_way_id=='169753571'&utc_timestamp=="2019-06-02T11:00:00.000Z"][order(utc_timestamp)][,!c("month","day","year","hour")]## utc_timestamp osm_way_id osm_start_node_id osm_end_node_id
## 1: 2019-06-02T11:00:00.000Z 169753571 1813307792 235637281
## 2: 2019-06-02T11:00:00.000Z 169753571 26876458 2777147163
## 3: 2019-06-02T11:00:00.000Z 169753571 2238699687 2777147163
## 4: 2019-06-02T11:00:00.000Z 169753571 235637281 1813307792
## 5: 2019-06-02T11:00:00.000Z 169753571 2238699541 1813307792
## 6: 2019-06-02T11:00:00.000Z 169753571 2777147163 26876458
## 7: 2019-06-02T11:00:00.000Z 169753571 2777147163 2238699687
## 8: 2019-06-02T11:00:00.000Z 169753571 2777147147 2238699687
## 9: 2019-06-02T11:00:00.000Z 169753571 2238699687 2777147147
## 10: 2019-06-02T11:00:00.000Z 169753571 2238699582 2777147147
## 11: 2019-06-02T11:00:00.000Z 169753571 2777147147 2238699582
## 12: 2019-06-02T11:00:00.000Z 169753571 2238699541 2238699582
## 13: 2019-06-02T11:00:00.000Z 169753571 2238699582 2238699541
## 14: 2019-06-02T11:00:00.000Z 169753571 1813307792 2238699541
## speed_kph_mean speed_kph_stddev
## 1: 21.007 17.470
## 2: 20.330 14.828
## 3: 16.792 13.527
## 4: 24.675 17.875
## 5: 26.493 20.579
## 6: 18.368 16.461
## 7: 24.360 18.828
## 8: 18.236 6.849
## 9: 26.236 20.184
## 10: 20.308 19.210
## 11: 26.810 21.513
## 12: 15.351 21.221
## 13: 26.450 21.985
## 14: 15.527 20.993Let’s check if there are no duplicates :
DT.Uber[,.(count=.N),by=.(osm_way_id,utc_timestamp,day,osm_start_node_id,osm_end_node_id)][order(-count)][,.(mean_count=mean(count),std_count=sd(count))]## mean_count std_count
## 1: 1 0All right, the count value is always equal to 1.
From now on, as our aim is to evaluate the overall trips density and speed, as for the sake of simplicity, we keep our scope on the osm_way_id level rather the direction within the osm_way_id, which by the way, and we can figure it out on the Uber website, is not easy to visualize.
As we saw previously thanks to the “structure” str command, the Uber table as 2,409,465 rows. Are those rows all valid, is there any missing data ? We can use the following operation to check that :
DT.Uber[,.(col=names(.SD),
nok= nok<-colSums(is.na(.SD)),
ok = .N -nok,
total = .N)]## col nok ok total
## 1: year 0 2409465 2409465
## 2: month 0 2409465 2409465
## 3: day 0 2409465 2409465
## 4: hour 0 2409465 2409465
## 5: utc_timestamp 0 2409465 2409465
## 6: osm_way_id 0 2409465 2409465
## 7: osm_start_node_id 0 2409465 2409465
## 8: osm_end_node_id 0 2409465 2409465
## 9: speed_kph_mean 0 2409465 2409465
## 10: speed_kph_stddev 0 2409465 2409465What have we done ? we first select the DT.Uber table, insert a comma because we do not want to filter the rows, then create four columns :
col: we use thenamesfunction to retrieve the list of column names of all the data.table columns (.SDfor SubsetData)nok: we compute the sum of non valid entries per column (.is.naon.SD), and use an intermediary variable assignment with the help of the<-operator (see 3.4.1 in the R Quick Tutorial)ok: logically, this is the difference between number of rows (.N) and thenoktotal: the total number of rows.
One good news : this table seems to be clean.
One more thing with this DT.Uber : the utc_timestamp is of class character, but we want it to be of type POSIXct, which is the standard datetime format in R. For this, we use the lubridate package with its ymd_hms method :
DT.Uber[,utc_timestamp:=ymd_hms(utc_timestamp)]
str(DT.Uber$utc_timestamp)## POSIXct[1:2409465], format: "2019-06-20 16:00:00" "2019-06-21 22:00:00" ...Alleluja, the parsing (i.e. conversion) from class character to POSIXT was painless, which is worth mentioning.
But, is this dataset really for June 2019 ?
DT.Uber[,.(min_datetime=min(utc_timestamp),max_datetime=max(utc_timestamp))]## min_datetime max_datetime
## 1: 2019-05-31 22:00:00 2019-06-30 21:00:00Seems so indeed.
Now we can set indexing on this table, in order to, similarly to the SQL indexes, speed up the operations :
setkey(DT.Uber,utc_timestamp,osm_way_id)OSM data
Now we can load the OSM shapefile for the ways elements, with the help of the sf package (which is considerably faster than the rgdal package for read operations)
OSM_sf <- sf::read_sf(dsn = "data/berlin_osm_shp/", layer = "gis_osm_roads_free_1")What have we done ? What is a shapefile ? we can look at its structure :
str(OSM_sf)## Classes 'sf', 'tbl_df', 'tbl' and 'data.frame': 165629 obs. of 11 variables:
## $ osm_id : chr "4045150" "4045194" "4045220" "4045223" ...
## $ code : int 5122 5122 5122 5122 5113 5114 5114 5122 5114 5122 ...
## $ fclass : chr "residential" "residential" "residential" "residential" ...
## $ name : chr "Waldstraße" "Ursula-Goetze-Straße" "Hönower Straße" "Gundelfinger Straße" ...
## $ ref : chr NA NA NA NA ...
## $ oneway : chr "B" "B" "B" "F" ...
## $ maxspeed: int 50 30 30 30 50 50 30 30 50 0 ...
## $ layer : num 0 0 0 0 0 0 0 0 0 0 ...
## $ bridge : chr "F" "F" "F" "F" ...
## $ tunnel : chr "F" "F" "F" "F" ...
## $ geometry:sfc_LINESTRING of length 165629; first list element: 'XY' num [1:13, 1:2] 13.6 13.6 13.6 13.6 13.6 ...
## - attr(*, "sf_column")= chr "geometry"
## - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA
## ..- attr(*, "names")= chr "osm_id" "code" "fclass" "name" ...Nice, we have here a table with the OSM_id which we can connect to the Uber osm_way_id, they are brothers ! But what kind of object is OSM_sf ?
class(OSM_sf)## [1] "sf" "tbl_df" "tbl" "data.frame"Well, a combination of sf, tbl_df, tbl and data.frame
The last column geometry contains as its name figures, the coordinates of each way id (that means how to draw the street with the help of multiple coordinates).
To calm down our excitment, we can plot a part of this shapefile with the use of the filter method (we do not want to plot the 165629 Polygons of all the ways !) Here we filter out the ways that are of class motorway and residential and the streets with names containing “Marx” :
plot(st_geometry(OSM_sf%>% filter(fclass=='motorway')),col='navy',reset=F)
plot(st_geometry(OSM_sf%>% filter(fclass=='residential')),col='lightblue',add=T)
plot(st_geometry(OSM_sf%>% filter(grepl('Marx',name))),col='red',add=T)
What we did here is first plot the motorway class, with the reset parameter set to FALSE, to allow the second and third plot calls with the residential class & name containing ‘Marx’ to be drawn on the same figure.
As a side note, we use the standard plot method of the sf package. One nice thing with sf is that you can also use the ggplot2 package for visualization. But in our case, the amount of elements to plot (>100000) make it very slow with ggplot2.
Now we that we have loaded our data in memory, we can start aggregating and merging those two datasets.
Merge and Aggregate the data
Merge the data
Remember the column maxspeed from the OSM_sf table ? We are going to combine the DT.Uber table with the OSM_sf to compare the Uber speed_kph_mean with the OSM maxspeed:
first we select only from the OSM_sf the fields of interest :
DT.max.speed <- OSM_sf %>% dplyr::select(osm_id,fclass,name,maxspeed)then we set this new table as a data.table, convert the column osm_id as numeric (because the osm_way_id from DT.Uber is already a numeric value, and finally define the index column :
setDT(DT.max.speed)
DT.max.speed[,osm_id:=as.numeric(osm_id)]
setkey(DT.max.speed,osm_id)And now, we merge this DT.max.speed table with the DT.Uber :
DT.max.speed <- merge(DT.max.speed,DT.Uber, by.x='osm_id',by.y='osm_way_id')with this new table we add a new column is.over that gives 1 if the mean_speed_kph is greater than the maxspeed allowed and 0 otherwise :
DT.max.speed[,is.over := as.numeric(is.over <- speed_kph_mean>maxspeed)]Out of sheer curiosity, how often is the speed limit not respected ?
DT.max.speed[,(ratio=sum(is.over)/.N)*100, ]## [1] 24.93969OK.
Now, we check how many ways have a speed limit defined :
DT.max.speed[,(ratio=sum(maxspeed>0)/.N)*100, ]## [1] 99.91157How does it looks like per maxspeed value :
DT.max.speed[, .(count = .N), by = .(maxspeed)][, percentage := count / sum(count) *
100][order(maxspeed)]## maxspeed count percentage
## 1: 0 2112 0.088425696
## 2: 10 4350 0.182126789
## 3: 20 236 0.009880902
## 4: 30 349198 14.620301234
## 5: 40 1430 0.059871565
## 6: 50 1846718 77.318808966
## 7: 60 36972 1.547952099
## 8: 70 188 0.007871227
## 9: 80 146229 6.122349009
## 10: 100 972 0.040695917
## 11: 120 41 0.001716597Fine, there are few ways without speed limit. (less than 0.09%).
Aggregate the data
Hang on, we are close the end, we still want to aggregate the data per way and hour of the day. For this, we are going to use the group by functionality via the by keyword, and create new variables : (take note that we filter the table on the ways that have an OSM maximum speed defined)
DT.max.speed.per.way.hour <-
DT.max.speed[maxspeed > 0][, .(
total_rows = .N,
ratio.over = sum(is.over) / (.N) * 100,
speed_kph_mean = speed_kph_mean <-
mean(speed_kph_mean),
maxspeed = maxspeed <-
mean(maxspeed),
speed_minus_max = speed_kph_mean - maxspeed,
name = first(name)
), by = .(osm_id, hour)]How does this new aggregated table looks like ? (The empty square brackets are a neat data.table trick to print it)
DT.max.speed.per.way.hour[]## osm_id hour total_rows ratio.over speed_kph_mean maxspeed
## 1: 4045243 0 60 11.66667 47.80583 50
## 2: 4045243 1 60 30.00000 49.01758 50
## 3: 4045243 2 46 30.43478 49.14030 50
## 4: 4045243 3 58 48.27586 49.89152 50
## 5: 4045243 4 40 42.50000 49.50612 50
## ---
## 126416: 699295574 2 3 0.00000 35.91000 50
## 126417: 699295574 3 3 0.00000 37.82367 50
## 126418: 699295574 16 1 0.00000 27.88300 50
## 126419: 699295574 4 1 0.00000 38.22100 50
## 126420: 699531029 8 1 0.00000 21.04500 50
## speed_minus_max name
## 1: -2.1941667 Frankfurter Allee
## 2: -0.9824167 Frankfurter Allee
## 3: -0.8596957 Frankfurter Allee
## 4: -0.1084828 Frankfurter Allee
## 5: -0.4938750 Frankfurter Allee
## ---
## 126416: -14.0900000 An der Wuhlheide
## 126417: -12.1763333 An der Wuhlheide
## 126418: -22.1170000 An der Wuhlheide
## 126419: -11.7790000 An der Wuhlheide
## 126420: -28.9550000 Pasewalker StraßeFor each OSM way, we have all hours of the day, the percentage of times the median speed was over the maximum speed allowed, and the delta between both.
Visualizations with ggplot2
We can plot a sample of this table to have an overview by filtering on the hour equal to 17h :
ggplot(DT.max.speed.per.way.hour[, name := as.factor(name)][hour == 17], aes(ratio.over, total_rows)) + geom_point(shape = 21, alpha = .4, aes(color = (name))) + facet_wrap(. ~ maxspeed) + theme(legend.position = 'None')
Here we just confirm what we saw in the aggregation section, it seems some maxspeed are not “standard” or very seldomly used by Uber. We can confirm this with a quick histogram :
ggplot(DT.max.speed.per.way.hour,aes(maxspeed))+ geom_histogram()+theme_bw()## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Indeed, 30,50 and 80 kph limits are our numbers.
We can drop the others rows :
DT.max.speed.per.way.hour <- DT.max.speed.per.way.hour[maxspeed %in% c(30,50,80)]Now focus on the maxspeed=50 kph:(the color represents a street name). Please notice here that we use the ggplotly function from the plotly package to make our ggplot2 chart interactive (under the hood, it is d3.js running, you can be proud of you, really.)
p <-
ggplot(DT.max.speed.per.way.hour[, name := as.factor(name)][hour == 17 &
maxspeed == 50 &
ratio.over < 15 &
ratio.over > 0], aes(ratio.over, total_rows)) + geom_point(shape = 1, alpha =
1, aes(color = (name))) + theme(legend.position = 'None')
ggplotly(hide_legend(p))What those curves could be ? How can those dots, which color corresponds to a street name, form inverse curves although they are not related ? For instance, the Müllerstraße dot on the plot is next to the Frankfürter Allee dot, and on the same fitting curve, although they are in two different districts of Berlin.
More prosaically, we can plot the over speed percentage in the day : For this, we just use our current table, and aggregate per hour of the day and compute the weighted ratio of over speed :
DT.max.speed.per.hour <- DT.max.speed.per.way.hour[,.(ratio.over=sum(ratio.over*total_rows)/sum(total_rows),mean_speed_minus_max=sum(speed_minus_max*total_rows)/sum(total_rows)),by=.(hour,maxspeed)][,maxspeed:=as.factor(maxspeed)]
DT.max.speed.per.hour[0:5]## hour maxspeed ratio.over mean_speed_minus_max
## 1: 0 50 14.80034 -10.042412
## 2: 1 50 17.21446 -9.231080
## 3: 2 50 22.51034 -8.057035
## 4: 3 50 25.58019 -7.430214
## 5: 4 50 31.03792 -6.464708We use here the ggthemes package to add some elegance and credibility to our charts with the help of The Economist theme :
ggplot(DT.max.speed.per.hour, aes(hour, ratio.over)) + geom_line(aes(color =
maxspeed), size = 1) + theme_economist() + ggtitle('speed infrigment % per hour of the day') +
scale_color_economist() + theme(plot.title = element_text(size = 12)) +
ylab('%') + xlab('hour of the day')
ggplot(DT.max.speed.per.hour, aes(hour, mean_speed_minus_max)) + geom_line(aes(color =
maxspeed), size = 1) + theme_economist() + ggtitle('difference between mean speed and max allowed speed per hour of the day') +
scale_color_economist() + theme(plot.title = element_text(size = 12)) +
ylab('difference in kph') + xlab('hour of the day')
Hey, but we forgot to look at the overall rides along the hour of the day ! How could we do that ? Just reuse the original DT.Uber table and do some aggregation :
DT.rides.per.hour <- DT.Uber[,.(total_rides=.N),by=.(hour)]
DT.rides.per.hour[0:5]## hour total_rides
## 1: 0 142254
## 2: 1 128207
## 3: 2 57126
## 4: 3 84035
## 5: 4 81893For the plot, we use an other ggplot trick ; the polar coordinates :
ggplot(DT.rides.per.hour, aes(hour, total_rides)) + geom_line(color = 'darkblue') +
theme_economist() + ggtitle('Sum of rides per hour along the day', subtitle = 'Warning : based on already aggregated data from Uber') +
scale_color_economist() + theme(
plot.title = element_text(size = 12),
legend.position = 'None',
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.ticks.x = element_blank()
) + ylab('') + xlab('') + coord_polar() 
Which gives us a relative idea of the rides volume in time.
Visualizations with Simple Features
Now that we have an idea of the content of our dataset, we can focus on its geospatial aspect.
Merge the data (again)
We first merge our DT.max.speed.per.way.hour table with the OSM shapefile :
df.Uber <- as.data.frame(DT.max.speed.per.way.hour[,name:=NULL])
OSM_sf.with.Uber <- merge(OSM_sf,df.Uber,by.x='osm_id',by.y='osm_id',all.y=T)Note that in order to merge both, we must convert our data.table DT.max.speed.per.way.hour to a data.frame.
Can we resist to look at the Uber data for the streets (ways) that are defined as ‘pedestrian’ ?
No.
OSM_sf.with.Uber %>% filter(fclass=='pedestrians')## Simple feature collection with 0 features and 16 fields
## bbox: xmin: NA ymin: NA xmax: NA ymax: NA
## epsg (SRID): 4326
## proj4string: +proj=longlat +datum=WGS84 +no_defs
## [1] osm_id code fclass name
## [5] ref oneway maxspeed.x layer
## [9] bridge tunnel hour total_rows
## [13] ratio.over speed_kph_mean maxspeed.y speed_minus_max
## [17] geometry
## <0 rows> (or 0-length row.names)A very clean dataset indeed, not a single row for ways defined by OSM as pedestrian.
How about the other types of ways ? We aggregate the data per class and compute the mean of the speed limit infrigment ratio :
DT.OSM.max.speed <- as.data.table(OSM_sf.with.Uber)
DT.OSM.max.speed[,.(total_fclass=.N, mean_ratio.over =round(mean(ratio.over),2)),by=.(fclass)][order(-mean_ratio.over)]## fclass total_fclass mean_ratio.over
## 1: unclassified 592 54.69
## 2: trunk 711 54.00
## 3: motorway 7807 53.81
## 4: trunk_link 10 40.00
## 5: residential 8940 29.58
## 6: motorway_link 890 24.58
## 7: primary 33527 21.55
## 8: secondary 52036 18.18
## 9: tertiary 15670 17.44
## 10: secondary_link 271 8.13
## 11: primary_link 132 2.27
## 12: tertiary_link 11 0.00In term of occurence, motorways are the most likely to witness speed limit infrigments.
Create an animation with the magick package :
With the shapefile enriched with our aggregated Uber data, we have a glance into it:
plot(subset(OSM_sf.with.Uber,hour==5)["total_rows"],col='darkblue',main='Rides at 5am')
Nice, but we also want to represent the frequency of those rides per way. For this, we set a new variable col that use the quantiles of the total_rows to set the color :
col <- findColours(classIntervals(
OSM_sf.with.Uber$total_rows, 4, style="quantile"),
smoothColors("tomato",98,"white"))Now try again with this col variable :
plot(subset(OSM_sf.with.Uber,hour==5)["total_rows"],col=col,main='Rides at 5am with quantiles color')## Warning in plot.sf(subset(OSM_sf.with.Uber, hour == 5)["total_rows"], col =
## col, : col is not of length 1 or nrow(x): colors will be recycled; use pal
## to specify a color palette
How about adding a black background ?
plot(subset(OSM_sf.with.Uber,hour==5)["total_rows"],col=col,main='Rides at 5am with quantiles colors and black background',bgc='black')## Warning in plot.sf(subset(OSM_sf.with.Uber, hour == 5)["total_rows"], col =
## col, : col is not of length 1 or nrow(x): colors will be recycled; use pal
## to specify a color palette
Ok, now we can write a methode to loop on each hour of the day, plot the map, and save it into a file :
Before that, we must adjust the geographical boundaries of each plot so that, when combined, they fit on the same rectangle :
# we create a new sf object to freeze the boundaries while looping on the hour :
bb <- st_bbox(OSM_sf.with.Uber)
print(bb)## xmin ymin xmax ymax
## 13.17176 52.39320 13.59680 52.61206a = st_sf( geom = st_sfc(st_point(c(bb$xmin,bb$ymin)), st_point(c(bb$xmax,bb$ymax))), crs = 4326)And now our looping method : uncomment the code to make it run
#
# for (i in unique(OSM_sf.with.Uber$hour)){
# png(paste0('plot/',as.character(i),"_rplot.png") )
# plot(a,axes=F,col='black',reset=F,bgc='black',main=paste0('Average Uber rides at ',stringr::str_pad(i,2,'left','0'),'H'))
# plot(subset(OSM_sf.with.Uber,hour==i)["total_rows"],add=T,axes=F,col=col)
# dev.off()
# }Once we have our 24 plots saved into files in the plot folder (make sure it exists before), we call the method to load those images, combine them and generate an animated gif :
createAnimation <- function() {
listfiles <-
paste0('plot/', sort(unique(OSM_sf.with.Uber$hour)), "_rplot.png")
images <- lapply(listfiles , image_read)
frames <- image_morph(image_join(images) , frames = 10)
animation <- image_animate(frames, fps = 2)
image_write(animation, "plot/Uber_total_rows.gif")
}The call to this method is commented as it is relatively long to process:
#createAnimation()And here is the final result :

Uber
Visualizations with Leaflet I
Plot density of rides
Let’s have a look at the distribution per hour of the day of the number of aggregated trips :
ggplot(OSM_sf.with.Uber,aes( as.factor(hour),total_rows)) + geom_boxplot()+ theme_economist()
So many outliers…
The leaflet package is the way to go when you want to implement interactive maps in R, especially when working in a Shiny project.
we start by defining the data we want to plot: the density of trips, at 5 am for street with more than 10 occurences, not motorway, neither tunnel :
data.to.plot <-
OSM_sf.with.Uber %>% filter(hour == 2 &
fclass != 'motorway' & tunnel == 'F')
colorPalette <-
colorQuantile("plasma",
data.to.plot$total_rows,
n = 5,
reverse = T)And here we go with Leaflet : (we filter on 5 am and use a CartoDB theme, more info here)
Now let’s add the coordinates of the nightclubs in Berlin. For this, we load an other shapefile, the one with the buildings informations, from the GeoFabrik folder :
OSM_sf_building <- sf::read_sf(dsn = "data/berlin_osm_shp/", layer = "gis_osm_pois_free_1")Let’s filter the night life amenities :
OSM_sf_building.night <- OSM_sf_building %>% filter(fclass %in% c("bar","bbq","biergarten","cafe","drinking_water","fast_food","food_court","pub","restaurant","brothel","casino","cinema","nightclub","stripclub","swingerclub","biergarten"))
ggplot(OSM_sf_building.night,aes(fclass))+ geom_bar(fill='steelblue')+theme_economist()+coord_flip()
We add the nightclub class data to the Leaflet plot :
leaflet(OSM_sf_building.night %>% filter(fclass %in% c('nightclub'))) %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addCircleMarkers(
stroke = F,
fill = T,
fillOpacity = 0.3,
weight = 0.5,
radius = 3,
color = 'white',
popup = ~ name,
label = ~ name,
layerId = OSM_sf_building.night$osm_id) %>% addPolylines(data=data.to.plot,
color = ~colorPalette(data.to.plot$total_rows),
weight = 1,
layerId = OSM_sf.with.Uber$osm_id)%>% addLegend(data=data.to.plot,"bottomright", pal = colorPalette, values = ~total_rows,
title = "Rides density quantiles",
labFormat = labelFormat(prefix = ""),
opacity = 1
)Visualizations with Leaflet II
Plot frequency of speed limit excesses
Now let’s procees the same way to visualize the frequency of speed exceses :
data.to.plot <-
OSM_sf.with.Uber %>% filter(hour == 2 & total_rows>50 &
fclass != 'motorway' & tunnel == 'F')
colorPalette <-
colorNumeric("Reds",
data.to.plot$ratio.over,
reverse = F)leaflet(data.to.plot) %>% addProviderTiles(providers$CartoDB.DarkMatter) %>% addPolylines(
color = ~colorPalette(data.to.plot$ratio.over),
weight = ~log(1+speed_minus_max),
label=~paste0(name,':',round(ratio.over,0),'% / ',round(speed_minus_max,0),' kph over in average'),
layerId = OSM_sf.with.Uber$osm_id)%>% addLegend("bottomright", pal = colorPalette, values = ~ratio.over,
title = "Speed excess frequency % ",
labFormat = labelFormat(suffix = " %"),
opacity = 1
)## Warning in log(1 + speed_minus_max): NaNs produced