Skip to content

Instantly share code, notes, and snippets.

@abachman
Created June 19, 2019 02:50
Show Gist options
  • Save abachman/0cebfbbfb9414d32479c5e95acf2f75c to your computer and use it in GitHub Desktop.
Save abachman/0cebfbbfb9414d32479c5e95acf2f75c to your computer and use it in GitHub Desktop.
Adafruit IO public feed data chart
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" />
<style>
body {
margin: 0; padding: 0;
}
.container {
width: 100vw;
height: 100vh;
}
</style>
<script>
var BLUE = 'rgb(54, 162, 235)'
fetch('https://io.adafruit.com/api/v2/abachman/feeds/temperature/data/chart').
then(function (response) { return response.json() }).
then(function (json) {
/*
Format the data so that Chart.js can consume it. Chart data from
IO comes in the form:
{
"data": [
[ timestamp, value ],
[ timestamp, value ],
...
]
}
With some additional fields describing the data. All we need for a
Chart.js chart is the data.
*/
// convert data to a format that Chart.js expects
var data = json.data.map(function (d) {
return { t: d[0], y: parseFloat(d[1]).toFixed(2) }
})
// set the canvas size based on the size of the container
var cvs = document.getElementById('chart')
var box = document.querySelector(".container")
var width = box.offsetWidth
var height = box.offsetHeight
cvs.width = width
cvs.height = height
console.log('loaded data', data[0])
try {
// based on the example at https://www.chartjs.org/samples/latest/scales/time/financial.html
// and documentation at https://www.chartjs.org/docs/latest/
var ctx = cvs.getContext('2d')
var mychart = new Chart(ctx, {
responsive: false,
type: 'bar', // spaces out the x-axis ticks
data: {
datasets: [{
label: "Temperature",
data: data,
pointRadius: 0,
type: 'line',
fill: false,
lineTension: 0.5,
borderWidth: 3,
borderColor: BLUE,
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
distribution: 'series',
gridLines: {
drawOnChartArea: false
},
ticks: {
source: 'data',
autoSkip: true,
},
time: {
minUnit: 'hour'
}
}],
}
}
})
} catch (err) {
console.error('chart error', err)
}
})
</script>
</head>
<body>
<div class="container">
<canvas id="chart"></canvas>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment