Creating abstract city maps for Leaflet usage

Leaflet is a great way to display spatial information in an interactive way. If you want to display the difference between different neighborhoods you would usually get the proper shapefiles on the web and connect your data to them. But sometimes it does not need detailed shapefiles and you want more abstraction to get your information across. I came up with the idea to draw my own little simplified polygons to get an abstract map of Hamburg.

AbtractHHtool

There are some great and free tools on the web to create your own polygons. I was using click2shp. You are just going to draw your polygons on a google map and afterwards you can export your polygons as a shapefile to use them from within R. Down below you find a little R script to display your polygons in a Shiny App.

#############################################################################################################################################
# PACKAGES
#############################################################################################################################################

require(leaflet)
require(shinythemes)
require(rgdal)
require(maptools)
require(rmapshaper)
require(shiny)
require(leaflet.extras)

#############################################################################################################################################
# UI
#############################################################################################################################################

shinyUI(
bootstrapPage(theme = shinytheme("united"),
 navbarPage(title="Where to live in Hamburg?",
 tabPanel("Karte",
 div(class="outer",

tags$style(type = "text/css", ".outer {position: fixed; top: 50px; left: 0; right: 0; bottom: 0; overflow: hidden; padding: 0}"),

leafletOutput("mymap", width = "100%", height = "100%")
)))))

#############################################################################################################################################
# SERVER
#############################################################################################################################################

shinyServer(
function(input, output, session) {

# setwd
setwd("YourPath")

# load your own shapes
hhshape <- readOGR(dsn = ".", layer = "click2shp_out_poly")

# load some data (could be anything)
data <- read.csv("anwohner.csv", sep = ";", header = T)
rownames(data) <- data$ID
hhshape <- SpatialPolygonsDataFrame(hhshape, data)

# remove rivers from sp file
hhshape <- hhshape[!(hhshape$Stadtteil %in% c("Alster","Elbe","Nix")), ]

# create a continuous palette function
pal <- colorNumeric(
 palette = "Blues",
 domain = hhshape@data$Anwohner
)

# plot map
output$mymap <- renderLeaflet({ leaflet(options = leafletOptions(zoomControl = FALSE, minZoom = 11, maxZoom = 11, dragging = FALSE)) %>%
 setView(lng = 9.992924, lat = 53.55100, zoom = 11) %>%
 addPolygons(data = hhshape,
  fillColor = ~pal(hhshape@data$Anwohner), fillOpacity = 1, stroke = T, color = "white", opacity = 1, weight = 1.2, layerId = hhshape@data$ID,
  highlightOptions = highlightOptions(color= "grey", opacity = 1, fillColor = "grey", stroke = T, weight = 12, bringToFront = T, sendToBack = TRUE),
  label=~stringr::str_c(Stadtteil,' ',"Anwohner:",formatC(Sicherheit, big.mark = ',', format='d')),
  labelOptions= labelOptions(direction = 'auto'))
})
})

This little R Code will give you the following result.

AbtractHH

Make sure you check out my Github for other data driven projects.

Advertisements

Shiny App for cultural hackathon

Recently I took part at Coding Durer, a five days international and interdisciplinary hackathon for art history and information science. The goal of this hackathon is to bring art historians and information scientists together to work on data. It is kind of an extension to the cultural hackathon CodingDaVinci where I participated in the past. I also wrote an article about CDV on this blog.

Logo_CodingDurer_300dpi-1-300x164

At CodingDurer we developed a Shiny App to explore the genre of church interior paintings developed in the Netherlands in the middle of the 17th century. There are hundreds of church interior paintings scattered across collections around the world. The research of this subject to date has focused mainly on particular artists or churches, rather than the overall genre and its network of artists and places. This project, born during the Coding Durer 2017, addresses this issue by providing a platform for further research on the paintings and creating an insight into the bigger picture of the genre for the first time. This visualization of over 200 paintings of 26 different churches by 16 different artists was created with the following research questions in mind:

  • In what places the artists were active and in what places did they depict church interior(s)?
  • Did the artists have ‘favourite’ church interiors?
  • In what places and when would the artists possibly meet?
  • What church interiors were depicted the most?
  • What church interiors were depicted by most artists?

durer1

The starting point of the project was a spreadsheet listing the paintings, artists, collections, etc. that was created for research purposes two years ago. This re-purposed data needed cleaning and additional information, e.g. IDs (artists, churches, paintings), locations (longitude, latitude), and stable URLs for images. You can see an image of the Shiny App above and try it out yourself here.

You can get the whole code on my Github along with other data driven projects.

Cultural data hackathon with Shiny and Leaflet

CodingDaVinci is the first German open cultural data hackathon that started in Berlin 2014. They bring together both cultural heritage institutions and the hacker & designer community to develop ideas and prototypes for the cultural sector and the public. In 2016 the hackathon took place in Hamburg and ran for a total of 10 weeks. Open cultural data is usually held by cultural heritage institutions such as galleries, libraries, archives and museums (GLAMs). A list of projects from 2016 can be seen on their website.

cdv-nord_kacheln-2016

As I was playing around with leaflet recently I wanted to take part at the hackathon and develop something around spatial data. Leaflet is one of the most popular open-source JavaScript libraries for interactive maps and there is a wonderful R package that makes it easy to integrate and control Leaflet maps in R. You can find a neat little github page that will let you get started with Leaflet easily.

In the end I took visitor data from the museums in Hamburg. The data captures group bookings from private persons, schools, universities and other educational institutions. I came up with the idea of a map which shows the amount of museum visits of schools per neighborhood. On another layer I also mapped the amount to students per neighborhood and plotted every school as a marker on the map. This way the user can find out in which areas of Hamburg the schools often visit the museums and which neighborhoods need to catch up.

bild2

I think this map is relevant because cultural education is an indispensable part of our education system, as it is essential to the dignity of a human and the free development of his personality (Article 22, UN Human Rights Charter). An important part of this is the school trip to the museum, in order to attract students to art and culture as well as to strengthen their personality formation and social competence by means of cultural education.

Make sure you try out the map. If you are interested in the code you can check out my Github.

Deploy your Shiny apps easily with shinyapps.io

shiny

In the past I created several shiny apps to display data interactively. Sometimes you might want to share your application with other people and do not have your own server nor the skills to set one up or pay to for it. If you just want to make your shiny app public without any big effort or money you definitely should check out shinyapps.io. They describe their self as a platform as a service (PaaS) for hosting Shiny web apps (applications).

# get package
require(rsconnect)

# change bundle size for bigger aps
options(rsconnect.max.bundle.size = 30000000000)

# set your parameters
mytoken <- "MyTokenID"
mysecret <- "MySecretID"
myname = "MyName" # you could use multiple free accounts 🙂

# connect your account
rsconnect::setAccountInfo(name=myname,
token=mytoken,
secret=mysecret)

# deploy your app
rsconnect::deployApp("Path to the folder of your APP")

To get started you will need the latest version of their rsconnect package. You also need to sign up for an account on their website to get your token and secret (essential for using the service). Being done with this you can configure your account using the setAccountInfo function and deploy your app with deployApp. Two things I struggled with you might want to know about. Put all your script and contents for the app in one folder and remove all setwd() from your scripts. If you have a big app use the rsconnect.max.bundle.size function to solve your size issues.

Make sure you check out my Github for other data driven projects.

Bike sharing usage with Leaflet and Shiny

My interactive map shows the bike sharing usage of StadtRAD, the bike sharing system in Hamburg – Germany. The data is available on the open data platform from Deutsche Bahn, the public railway company in Germany. The last new StadtRAD station was put into operation in May 2016, that is why a have chosen to display the usage of June 2016. The brighter the lines, the more bikes have been cycled along that street.

c19fodkw8aa_d-l

From data processing and spatial analysis to visualization the whole project was done in R. I have used the leaflet and shiny package to display the data interactively. The bikes themselves don’t have GPS, so the routes are estimated on a shortest route basis using the awesome cyclestreets API. The biggest challenge has been the aggregation of overlapping routes. I found the overline function from the stplanr package very helpful. It converts a series of overlaying lines and aggregates their values for overlapping segments. The raw data file from Deutsche Bahn is quite huge so I struggled to import the data into R to process it. In the end the read.csv.sql function from the sqldf package did the job.

You can find the whole code from processing to the shiny functions on my github. The code could easily be used to map other spatial data, for example the car sharing data from car2go which is available via their API. This might be a future project.