The data from the Federal Statistical Office of Switzerland are available in the JSON-stat format. In the example, Police crime statistics are visualized in a bar chart using ChartJS.
Last active
March 19, 2021 20:19
-
-
Save badosa/7148589924ca07c2ca076eda4a359661 to your computer and use it in GitHub Desktop.
Crimes in Switzerland
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="https://cdn.jsdelivr.net/npm/jsonstat@0.13.13"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.js"></script> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
</head> | |
<body> | |
<div class="chart-container" style="position: relative; height:90vh; width:90vw"> | |
<canvas id="chart"></canvas> | |
</div> | |
<script> | |
var | |
url="https://www.pxweb.bfs.admin.ch/api/v1/en/px-x-1903020100_101/px-x-1903020100_101.px", | |
query='{ "query": [ { "code": "Kanton", "selection": { "filter": "item", "values": [ "8100" ] } }, { "code": "Ausführungsgrad", "selection": { "filter": "item", "values": [ "1", "2" ] } } ], "response": {"format": "json-stat2"}}', | |
ctx=document.getElementById("chart").getContext("2d") | |
; | |
$.ajax({ | |
type: "POST", | |
url: url, | |
data: query, | |
success: function( json ) { | |
var | |
ds=JSONstat(json).Dataset(0), | |
time=ds.Dimension({role: "time"}, false)[0], | |
completion=ds.Dimension("Ausführungsgrad"), | |
completedId="1", | |
attemptedId="2", | |
myChart=new Chart(ctx, { | |
type: "bar", | |
data: { | |
labels: time, | |
datasets: [{ | |
label: completion.Category(completedId).label, | |
data: ds.Data({"Ausführungsgrad": completedId}, false), | |
backgroundColor: "rgb(139, 0, 0)" | |
}, | |
{ | |
label: completion.Category(attemptedId).label, | |
data: ds.Data({"Ausführungsgrad": attemptedId}, false), | |
backgroundColor: "rgb(90, 0, 0)" | |
} | |
] | |
}, | |
options: { | |
title: { | |
display: true, | |
fontSize: 20, | |
text: "Criminal offences registered by the police in Switzerland" | |
}, | |
legend: { | |
display: false, | |
}, | |
tooltips: { | |
mode: "index", | |
intersect: false | |
}, | |
scales: { | |
xAxes: [{ | |
stacked: true, | |
}], | |
yAxes: [{ | |
stacked: true | |
}] | |
} | |
} | |
}) | |
; | |
}, | |
error: function() { | |
$("body").html("There was an error while connecting to the data provider. Please, try later."); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment