Zürich Statistical Office collects data on the city and its residents. This data is published as Linked Data.
In this tutorial, we will show how to work with Linked Data. Mainly, we will see how to work with population dataset.
We will look into how to query, process, and visualize it.
Population data is published as Linked Data thatcan be accessed with SPARQL queries.
You can send queries using HTTP requests. The API endpoint is https://ld.stadt-zuerich.ch/query.
Let's use SparqlClient
from graphly to communicate with the database.
Graphly will allow us to:
pandas
or geopandas
# Uncomment to install dependencies in Colab environment
#!pip install git+https://github.com/zazuko/graphly.git
import re
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from graphly.api_client import SparqlClient
def natural_keys(txt: str) -> list[int]:
"""Extracts the digits from string
Args:
txt: string with digits
Returns:
list[int] digits in string
"""
return [int(s) for s in txt.split() if s.isdigit()]
sparql = SparqlClient("https://ld.stadt-zuerich.ch/query")
sparql.add_prefixes({
"schema": "<http://schema.org/>",
"cube": "<https://cube.link/>",
"property": "<https://ld.stadt-zuerich.ch/statistics/property/>",
"measure": "<https://ld.stadt-zuerich.ch/statistics/measure/>",
"collection": "<https://ld.stadt-zuerich.ch/statistics/collection/>",
"skos": "<http://www.w3.org/2004/02/skos/core#>",
"ssz": "<https://ld.stadt-zuerich.ch/statistics/>"
})
SPARQL queries can become very long. To improve the readibility, we will work wih prefixes.
Using the add_prefixes
method, we define persistent prefixes.
Every time you send a query, graphly
will automatically add the prefixes for you.
Let's find the number of inhabitants in different parts of the city. The population data is available in the BEW
data cube.
The query for the number of inhabitants in different city districts, over time looks as follows:
query = """
SELECT ?time ?place ?count
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE {
ssz:BEW a cube:Cube;
cube:observationSet/cube:observation ?observation.
?observation property:RAUM ?place_uri ;
property:TIME ?time ;
measure:BEW ?count .
?place_uri skos:inScheme <https://ld.stadt-zuerich.ch/statistics/scheme/Kreis> ;
schema:name ?place .
FILTER regex(str(?place),"ab|Stadtgebiet vor")
}
ORDER BY ?time
"""
df = sparql.send_query(query)
df.head()
Let's visualize the number of inhabitants per district. To do this, we will aggregate the numbers per place
.
The cleaned dataframe becomes:
df.place = df.place.apply(lambda x: re.findall('Kreis \d+', x)[0])
df = pd.pivot_table(df, index="time", columns="place", values="count")
df.dropna(inplace=True)
df = df[df.columns[np.argsort(-df.iloc[0,])]]
df = df.reset_index().rename_axis(None, axis=1)
df.head()
And now we can graph it using a line plot or a histogram.
sorted_df = df.reindex(sorted(df.columns, key=natural_keys), axis=1)
fig = px.line(sorted_df, x="time", y = sorted_df.columns)
fig.update_layout(
title='Population in Zürich Districts',
title_x=0.5,
yaxis_title="inhabitants",
xaxis_title="Years",
legend_title="District"
)
fig.show("notebook")