Created
February 18, 2019 16:09
-
-
Save ramiroaznar/da1dbd1d4f16adbd3a1e855d1686a6cb to your computer and use it in GitHub Desktop.
CARTO.js Histogram Dataview and Chart.js
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"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>CARTO.js Histogram Dataview and Chart.js</title> | |
<!-- Include Leaflet --> | |
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script> | |
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"> | |
<!-- Include CARTO.js --> | |
<script src="https://libs.cartocdn.com/carto.js/v4.1.10/carto.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/13.1.0/nouislider.min.js"></script> | |
<link href="https://carto.com/developers/carto-js/examples/maps/public/style.css" rel="stylesheet"> | |
<link href="https://cdnjs.cloudflare.com/ajax/libs/noUiSlider/13.1.0/nouislider.min.css" rel="stylesheet"> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> | |
<style> | |
body { | |
margin: 0; | |
padding: 0; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="chart" width="400" height="100"></canvas> | |
<script> | |
const client = new carto.Client({ | |
apiKey: 'default_public', | |
username: 'ramirocartodb' | |
}); | |
const source = new carto.source.SQL('select * from world_borders'); | |
const histogramDataview = new carto.dataview.Histogram(source, 'pop2005', {bins: 10}); | |
const histogramElement = document.getElementById('chart'); | |
const histoChart = new Chart(histogramElement, { | |
type: "bar", | |
data: { | |
datasets: [{ | |
label: 'Frequency', | |
data: [], | |
backgroundColor: [ | |
'#fcde9c','#faa476','#f0746e','#e34f6f','#dc3977','#b9257a','#7c1d6f' | |
] | |
}] | |
} | |
}); | |
client.addDataview(histogramDataview); | |
histogramDataview.on('dataChanged', (data) => { | |
histoChart.data.labels = data.bins.map(x => `${x.start} to ${x.end}`); | |
histoChart.data.datasets.forEach((dataset) => { | |
dataset.data = data.bins.map(x => x.freq); | |
}); | |
histoChart.update(); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment