← All Articles A Product of Kinsa Creative

Creating a chart of monetary values in chart.js 4

Assuming the values are stored as numerical values, when charting, this prepends the values with a dollar sign in the tooltip and on the y-axis scale:

const drawBarChart = ( canvasId ) => {
    const data = [];
    const labels = [];

    const ctx = document.getElementById( canvasId );

    const chart = new Chart( ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [ {
                data: data,
            } ]
        },
        options: {
            plugins: {
                tooltip: {
                    enabled: true,
                    callbacks: {
                        label: function ( context ) {
                            let label = context.dataset.label || '';

                            if ( context.parsed.y !== null ) {
                                label += "$" + context.parsed.y;
                            }

                            return label;
                        }
                    }
                }
            },
            scales: {
                y: {
                    ticks: {
                        callback: function ( value, index, values ) {
                            if ( index !== 0 && index !== values.length - 1 ) {
                                return "$" + value;
                            } else {
                                return undefined;
                            }
                        },
                    }
                }
            },
        }
    } );

    return chart;
}

To use it, in the HTML, after loading the chart.js library, create the chart, populate it with new data, and update. There are other ways to do this, but this allows the labels and dataset to be written into the template at the view level.



Feedback?

Email us at enquiries@kinsa.cc.