Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save glimpsedchaos/8f09b8c2c52e253d27771d27b0e30dba to your computer and use it in GitHub Desktop.
Save glimpsedchaos/8f09b8c2c52e253d27771d27b0e30dba to your computer and use it in GitHub Desktop.
Chart.js Chart Graphs - Trees - v3
<div><canvas id="dh"></canvas></div>
<div><canvas id="dv"></canvas></div>
<div><canvas id="f"></canvas></div>
const data = `https://raw.githubusercontent.com/sgratzl/chartjs-chart-graph/master/samples/tree.json`;
function createChart(nodes, id, type, orientation) {
new Chart(document.getElementById(id).getContext("2d"), {
type,
data: {
labels: nodes.map((d) => d.name),
datasets: [{
pointBackgroundColor: 'steelblue',
pointRadius: 5,
data: nodes.map((d) => Object.assign({}, d)),
}]
},
options: {
dragData: true,
dragX: true,
tree: {
orientation
},
layout: {
padding: {
top: 5,
left: 5,
right: 40,
bottom: 20
}
},
plugins: {
legend: {
display: false
},
datalabels: {
align: orientation === 'vertical' ? 'bottom' : 'right',
offset: 6,
backgroundColor: 'white',
formatter: (v) => {
return v.name;
}
}
},
}
});
}
fetch(data).then((r) => r.json()).then((nodes) => {
createChart(nodes, 'dh', 'dendogram', 'horizontal');
createChart(nodes, 'dv', 'dendogram', 'vertical');
createChart(nodes, 'f', 'forceDirectedGraph', 'vertical');
});
<script src="https://unpkg.com/chart.js@3"></script>
<script src="https://unpkg.com/chartjs-chart-graph@3"></script>
body {
width: 100vw;
height: 100vh;
display: grid;
grid-template-rows: repeat(2, 1fr);
grid-template-columns: repeat(2, 1fr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment