Site icon R-bloggers

Mappa choropleth eventi di musica a Roma

[This article was first published on R – SLOW DATA, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Dove si svolgono gli eventi musicali a Roma?

Prendiamo una settimana qualsiasi e visualizziamo, con R, gli eventi su una mappa di Roma divisa per zone urbanistiche. L’API di Allevents è un’ottima e per recuperare i dati sugli eventi di Facebook. In questo studio si analizzano gli eventi classificati come ‘parties’, ‘music’ o ‘concerts’. Per il workflow completo dietro questo esercizio, incluso l’estrazione dati con Python e la pulizia dei dati, visita questa repo su GitHub.

 

Libraries

# Libraries
library(RColorBrewer)
library(colorspace)
library(rgdal)
library(maptools)
library(PBSmapping)
library(dplyr)
library(rgeos)
library(leaflet)
library(htmlwidgets)
library(dplyr)
library(htmltools)
library(leaflet)
library(leaflet.extras)
library(ggplot2)

 

Lettura dei dati

Ora leggiamo i dati e gli shape files. Puoi scaricare i shapefile con le zone urbanistiche di Roma qui. Lo shape file del fiume Tevere è esportato da OSM. I dati sugli eventi sono estratti dall’API di allevents.in (controlla questa repo Github per visionare il codice Python e R che pulisce i dati sugli eventi).

# Read shapefile with borders of "zone urbanistiche" (roman boroughs)
zu <- readOGR(dsn = "./shapes", layer = "ZU_COD")

# change CRS for ZU shape file to coicide with OSM data
crslonglat = CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
zu <- spTransform(zu, CRS=crslonglat)

# Tiber river shape may look nice on the map
tevere <- readOGR(dsn = "./shapes/tevere.geojson",
                  layer = "OGRGeoJSON")

tevere <- spTransform(tevere, CRS=crslonglat)

# import events data
load("./data/cleaned_data.RData")
coords <- SpatialPoints(week_events_rome[, c("lon", "lat")], proj4string = crslonglat)
events <- SpatialPointsDataFrame(coords, week_events_rome)

# quick map to check all layers are fine
ggplot() +
  geom_polygon(data = zu, 
               aes(x = long, y = lat, group = group), 
               col = "grey", fill = "grey90", alpha = 0.5) +
  geom_path(data = tevere, 
            aes(x = long, y = lat, group = group),
            col = "blue") + 
  geom_point(data = week_events_rome, aes(x = lon, y = lat), 
             col = "red")

# only one point seems to lay outside of the boroughs
bbox(zu)
bbox(events)

 

Spatial elaboration

Prima di poter visualizzare una mappa di tipo choropleth c’è bisogno di aggregare i dati con una spatial join

# Spatial join many-to-one
events@data$event_id <- as.factor(events@data$event_id)
events_agg <- aggregate(x = events["event_id"], by = zu, FUN = length)

# The above code identifies which ZU polygon (boroughs) each event is located in and groups them accordingly 
zu$n_events <- events_agg$event_id

# Some boroughs has no events. Let's replace NAs with 0s 
zu@data[is.na(zu@data$n_events),"n_events"] <- 0

 

Visualization

Ora abbiamo tutte le informazioni di cui abbiamo bisogno per produrre la mappa

# we'll use some nice background from mapbox
MAPBOX_ACCESS_TOKEN <- 'YOUR-MAPBOX-TOKEN-HERE'

# preparing labels 
labels <- sprintf(
  "<strong>%s</strong><br/>%g Events / Week",
  zu$Name, zu$n_events
) %>% lapply(htmltools::HTML)

# find breaks for choropleth map colors
hist(zu@data$n_events, nclass = 50)

bins <- c(0, 1, 3, 5, 10, 15, 20, Inf)
pal <- colorBin("Reds", domain = zu$n_events, bins = bins)

# leaflet choropleth
m <- leaflet(zu) %>%
  setView(12.55, 41.9, 10) %>%
  addProviderTiles("MapBox", options = providerTileOptions(
    id = "mapbox.light",
    accessToken = MAPBOX_ACCESS_TOKEN))%>% 
  addPolygons(
    fillColor = ~pal(n_events),
    weight = 1,
    opacity = 1,
    color = "white",
    fillOpacity = 0.7,
    highlight = highlightOptions(
      weight = 5,
      color = "#666",
      dashArray = "",
      fillOpacity = 0.7,
      bringToFront = TRUE),
    label = labels,
    labelOptions = labelOptions(
      style = list("-weight" = "normal", padding = "3px 8px"),
      textsize = "15px",
      direction = "auto")) %>%
  addPolylines(data = tevere, col = "blue") %>%
  addControl("<P>Source: <a style='-size:7;' href=https://allevents.in/ target=_blank>allevents</a><br/>20-27/03/17<br/>Music/Parties/Concerts</P>",
             position='topright') %>%
  addScaleBar(position = c("bottomleft")) %>%
  addLegend(pal = pal, values = ~n_events, opacity = 0.7, title = "N. events",
            position = "bottomright")

 

Export

# if you wish to save the map as a html widget
saveWidget(widget = m, file = "events_rome.html", selfcontained = FALSE)

The post Mappa choropleth eventi di musica a Roma appeared first on SLOW DATA.

To leave a comment for the author, please follow the link and comment on their blog: R – SLOW DATA.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.