Skip to content

Instantly share code, notes, and snippets.

@luisoos
Last active April 12, 2022 12:28
Show Gist options
  • Save luisoos/27348817f8de369ee5786acbbdd9e7fe to your computer and use it in GitHub Desktop.
Save luisoos/27348817f8de369ee5786acbbdd9e7fe to your computer and use it in GitHub Desktop.
Generating a line chart in Chart.js from a external JSON file in vanilla JavaScript
<!-- Importing JS -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<script type="text/javascript" src="index.js"></script>
// This script will turn external data from a JSON file into a Chart.js chart.
getData();
async function getData() {
const response = await fetch('data.json');
const data = await response.json();
var length = data.length;
labels = [];
values = [];
for (var i = 0; i < length; i++) {
labels.push(data[i].object1);
values.push(data[i].object2);
}
new Chart(document.getElementById("myChart"), {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: "Label",
backgroundColor: [
"#715f8dBF",
"#715f8d99"
],
data: values
}
]
},
options: {
scales: {
y: {
beginAtZero: true
}
},
font: { // Setting a custom font family for the chart
fontFamily: " -apple-system, 'Helvetica Neue', BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica', sans-serif "
},
responsive: true,
maintainAspectRatio: true,
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment