Embed chart.js visualization in Ghost

Embed chart.js visualization in Ghost

There exist a variety of web visualization frameworks to choose from. Each of which has its own merits. I'm going to show a simple example of how to embed beautiful Charts into your Ghost posts using chart.js.

All of the following code can be placed within a single HTML block.

First, fetch the chart.js library from the CDN.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js"> </script>

Create a placeholder canvas for the chart. Use div to make the resizing easier for the Ghost template. Take a note of the id that you give the canvas. It is used in the next step, when we create the actual chart.

<div>
    <canvas id="chartId"></canvas>
</div>

We have now the library and placeholder ready, and we can create the actual chart. Here, we use the same charts as in the (Getting started tutorial)[https://www.chartjs.org/docs/latest/] of chart.js.

<script>
    var ctx = document.getElementById("chartId");
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
</script>

It's that simple to embed a basic chart into your Ghost posts. The end result looks like this