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")
fig = px.histogram(df, x="time", y=df.columns, barnorm="percent")
fig.update_layout(
title='Population in Zürich Districts',
title_x=0.5,
yaxis_title="% of inhabitants",
xaxis_title="Years",
legend_title="District"
)
fig['layout']['yaxis']['range']= [0,100]
fig.show()
Let's find the number of foreign and swiss inhabitants. The share of swiss/non-swiss population is available in the ANT-GGH-HEL
data cube. The population count is available in BEW
data cube.
The query for number of inhabitants and foreigners share over time looks as follows:
query = """
SELECT ?time (SUM(?pop_count) AS ?pop) (SUM(?foreigners_count)/SUM(?pop_count) AS ?foreigners)
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE {
ssz:BEW a cube:Cube;
cube:observationSet/cube:observation ?obs_bew.
?obs_bew property:TIME ?time ;
property:RAUM ?place_uri;
measure:BEW ?pop_count .
ssz:ANT-GGH-HEL a cube:Cube;
cube:observationSet/cube:observation ?obs_ant.
?obs_ant property:TIME ?time ;
property:RAUM ?place_uri;
measure:ANT ?ratio .
?place_uri skos:inScheme <https://ld.stadt-zuerich.ch/statistics/scheme/Kreis> ;
schema:name ?place .
BIND((?pop_count * ?ratio/100) AS ?foreigners_count)
}
GROUP BY ?time
ORDER BY ?time
"""
df = sparql.send_query(query)
df.head()
And now lets visualize the data using absolute numbers as well as percentages.
fig = make_subplots(rows=2, cols=1)
fig.append_trace(go.Scatter(x=df["time"],y=df["pop"],
name="Total population",
marker_color=px.colors.qualitative.Vivid[7],
showlegend=False,
), row=1, col=1)
fig.append_trace(go.Bar(x=df["time"],y=(1-df["foreigners"])*100,
name="swiss",
marker_color=px.colors.qualitative.Vivid[3]
), row=2, col=1)
fig.append_trace(go.Bar(x=df["time"],y=df["foreigners"]*100,
name="foreign",
marker_color=px.colors.qualitative.Vivid[9]
), row=2, col=1)
fig['layout']['yaxis']['title']='inhabitants'
fig['layout']['yaxis2']['title']='Population share in %'
fig['layout']['yaxis2']['range']= [0,100]
fig.update_layout(height=800, title={"text": "Population in Zürich", "x": 0.5}, barmode = "stack",
legend = {"x": 1, "y": 0.37})
fig.show()
Let's find the number of inhabitants in different age groups. The population count per age group is available in the BEW-ALT-HEL-SEX
data cube.
The query for the number of inhabitants in various age buckets over time looks as follows:
query = """
SELECT ?time ?age (SUM(?measure) AS ?count)
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE {
ssz:BEW-ALT-HEL-SEX a cube:Cube;
cube:observationSet/cube:observation ?observation.
?observation property:TIME ?time ;
property:ALT ?age_uri ;
measure:BEW ?measure .
collection:1-Jahres-Altersklasse skos:member ?age_uri.
?age_uri schema:name ?age .
}
GROUP BY ?time ?age
ORDER BY asc(?time)
"""
df = sparql.send_query(query)
df.head()
Let's calculate the population share for each age group. The dataframe becomes:
df["year"] = df.time.apply(getattr, args=("year", ))
df["count"] = df.groupby(["year"]).transform(lambda x: (x/x.sum())*100)
df['age'] = df['age'].apply(lambda x: int(str(x.split(" ")[0])))
df = df.sort_values(by=["year", "age"]).reset_index(drop=True)
df.head()
And lets visualize it using an interactive plot.
fig = px.bar(df, x="age", y="count", animation_frame="year", range_y=[0, 3], range_x=[0, df.age.max()])
fig.update_layout(
title='Population Distribution',
title_x=0.5,
yaxis_title="Population share in %",
xaxis_title="Age",
legend_title="District"
)
fig.show()
Let's take a look at age distribution among swiss and foreign inhabitants. We can find this data in the BEW-ALT-HEL-SEX
data cube.
The query for number of inhabitants in various age buckets, with their origin, over time looks as follows:
query = """
SELECT ?age ?origin (SUM(?measure) AS ?count)
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE {
ssz:BEW-ALT-HEL-SEX a cube:Cube;
cube:observationSet/cube:observation ?observation.
?observation property:TIME ?time ;
property:ALT/schema:name ?age;
measure:BEW ?measure ;
property:HEL/schema:name ?origin .
collection:1-Jahres-Altersklasse skos:member ?age_uri.
?age_uri schema:name ?age .
FILTER (?time = "2017-12-31"^^xsd:date)
}
GROUP BY ?age ?origin
ORDER BY asc(?age)
"""
df = sparql.send_query(query)
df.head()
Let's calculate the population share for each origin and age group. The dataframe becomes:
df["age"] = df["age"].apply(lambda x: int(str(x.split(" ")[0])))
df["count"] = df[["origin", "count"]].groupby(["origin"]).transform(lambda x: x/x.sum()*100)
df = df.sort_values(by=["age"]).reset_index(drop=True)
df.loc[df["origin"]=="Ausland", "origin"] = "foreign"
df.loc[df["origin"]=="Schweiz", "origin"] = "swiss"
df.head()
fig = px.bar(df, x="age", y="count",
barmode="overlay", range_y = [0,4], color="origin")
fig.update_layout(
title='Population Distribution',
title_x=0.5,
yaxis_title="Population share in %",
xaxis_title="Age",
legend_title="Origin"
)
fig.show()
Let's take a look at the age distribution for female and male inhabitants. We can find this data in the BEW-ALT-HEL-SEX
data cube.
The query for number of inhabitants in various age buckets, with their sex, over time looks as follows:
query = """
SELECT ?time ?sex ?age (SUM(?measure) AS ?count)
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE {
ssz:BEW-ALT-HEL-SEX a cube:Cube;
cube:observationSet/cube:observation ?observation.
?observation property:TIME ?time ;
measure:BEW ?measure ;
property:SEX/schema:name ?sex ;
property:ALT ?age_uri .
collection:1-Jahres-Altersklasse skos:member ?age_uri.
?age_uri schema:name ?age .
}
GROUP BY ?time ?sex ?age
ORDER BY asc(?time)
"""
df = sparql.send_query(query)
df.head()
Let's create a dataframe where one row represents one observation. It will allow us to use violin plots for our dataframe.
The dataframe becomes:
df.loc[df["sex"]=="weiblich", "sex"] = "female"
df.loc[df["sex"]=="männlich", "sex"] = "male"
df['age'] = df['age'].apply(lambda x: str(x.split(" ")[0])).astype(int)
df["year"] = df.time.apply(getattr, args=("year", )).astype(str)
df = df.sort_values(by=["year", "age"]).reset_index(drop=True)
df = df[(df.year == df.year.max()) | ((df.year == df.year.min()))]
df = df[["sex", "age", "year"]].loc[df.index.repeat(df["count"])].reset_index(drop=True)
df.head()
fig = px.violin(df, y="age", x="year", color="sex", violinmode="overlay")
fig.data[0].update(span = [0, 105], spanmode='manual')
fig.data[1].update(span = [0, 105], spanmode='manual')
fig.update_layout(title={"text": "Population distrubution", "x": 0.5})
fig.show()
fig = go.Figure()
fig.add_trace(go.Violin(x=df['sex'][df['year'] == "2002"],
y=df['age'][df['year'] == "2002"],
legendgroup='2002', scalegroup='2002', name='2002',
side='negative',
line_color='blue',
span = [0, 105],
spanmode='manual'))
fig.add_trace(go.Violin(x=df['sex'][df['year'] == "2017"],
y=df['age'][df['year'] == "2017"],
legendgroup='2017', scalegroup='2017', name='2017',
side='positive',
line_color='orange',
span = [0, 105],
spanmode='manual'))
fig.update_traces(meanline_visible=True)
fig.update_layout(title={"text": "Population distrubution", "x": 0.5}, yaxis_title="age")
fig.show()
Let's compare real estate prices and number of inhabitants over time. We will need to work with population and real estate data sets. The population data is available in the BEW
data cube. The real estate prices are in the QMP-EIG-HAA-OBJ-ZIM
data cube.
The query for the number of inhabitants and the housing prices over time looks as follows:
query="""
SELECT *
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE{
{
SELECT ?time (SUM(?pop_count) AS ?pop)
WHERE {
ssz:BEW a cube:Cube;
cube:observationSet/cube:observation ?obs_bew.
?obs_bew property:TIME ?time ;
property:RAUM ?place_uri_pop;
measure:BEW ?pop_count .
?place_uri_pop skos:inScheme <https://ld.stadt-zuerich.ch/statistics/scheme/Kreis> ;
schema:name ?place_pop .
FILTER regex(str(?place_pop),"ab|Stadtgebiet vor")
}
GROUP BY ?time
}
{
SELECT ?time (AVG(?quote) AS ?price)
WHERE {
ssz:QMP-EIG-HAA-OBJ-ZIM a cube:Cube;
cube:observationSet/cube:observation ?obs_apt.
?obs_apt property:TIME ?time ;
property:RAUM ?place_uri_apt;
measure:QMP ?quote .
?place_uri_apt skos:inScheme <https://ld.stadt-zuerich.ch/statistics/scheme/Kreis> ;
schema:name ?place_apt .
FILTER (?quote > 0)
FILTER regex(str(?place_apt),"ab|Stadtgebiet vor")
}
GROUP BY ?time
ORDER BY ?time
}
}
"""
df = sparql.send_query(query)
df.head()
# Create figure with secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# Add traces
fig.add_trace(
go.Scatter(x=df["time"], y=df["pop"], name="inhabitants"),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=df["time"], y=df["price"], name="price per m<sup>2</sup>"),
secondary_y=True,
)
# Layout
fig.update_layout(title={"text": "Population and real estate prices", "x": 0.5})
fig.update_yaxes(title_text="population", secondary_y=False)
fig.update_yaxes(title_text="price per m<sup>2</sup>", secondary_y=True)
fig.show()
The Statistical Office reports the number of deaths and the cause. Let's try to understand what are the main causes of death in Zurich.
This data is available in the GES-SEX-TOU
data cube.
The query for death cause and its broader category for the year 2015 looks as follows:
query = """
SELECT ?tou ?tou_broader (SUM(?ges) AS ?deaths)
FROM <https://lindas.admin.ch/stadtzuerich/stat>
WHERE {
ssz:GES-SEX-TOU a cube:Cube;
cube:observationSet/cube:observation ?obs.
?obs property:TIME ?time ;
property:TOU ?tou_uri;
measure:GES ?ges .
?tou_uri schema:name ?tou ;
skos:broader/schema:name ?tou_broader .
MINUS {?three_level_tou skos:broader ?tou_uri .}
FILTER (?time = "2015-12-31"^^xsd:date)
}
GROUP BY ?tou ?tou_broader
HAVING (?deaths > 0)
ORDER BY ?tou_broader
"""
df = sparql.send_query(query)
df.head()
Let's aggregate those results under more meaningful group names.
df.loc[(df.tou == "andere infektiöse Krankheiten"), "tou_broader"] = ""
df.loc[(df.tou == "andere infektiöse Krankheiten"), "tou"] = "Infektiöse Krankheiten"
df.loc[(df.tou == "Alkoholische Leberzirrhose"), "tou_broader"] = ""
df.loc[(df.tou == "Unbekannt"), "deaths"] = df.loc[(df.tou_broader == "Übrige"), "deaths"].sum()
df.loc[(df.tou == "Unbekannt"), "tou_broader"] = ""
df.loc[(df.tou_broader == "Krebskrankheiten/Bösartige Neubildungen"), "tou_broader"] = "Krebskrankheiten"
df = df.drop(df[df.tou == "Übrige (ohne unbekannte Todesursachen)"].index)
fig = px.treemap(df, path=['tou_broader', "tou"], values='deaths')
fig.update_layout(title={"text": "Causes of Death in 2015", "x": 0.5})
fig.show()