JSFiddle - React, Tailwind, and code Playground

by karthick Chandran

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.5.0/chart.min.js"></script>
 <div style="width: 80%; margin: auto;">
        <canvas id="myChart"></canvas>
    </div>

JavaScript

const labels = ['2015', '2016', '2017', '2018', '2019', '2020', '2021', '2022', '2023', '2024'];

const data = {
  labels: labels,
  datasets: [{
    label: 'KiwiSaver Balance (Purple)',
    data: [10000, 11500, 13200, 15000, 17500, 19800, 22500, 25000, 28000, 31000],
    borderColor: 'rgb(128, 0, 128)', // Purple color
    backgroundColor: 'rgba(128, 0, 128, 0.5)',
    yAxisID: 'y1',
    type: 'line',
    tension: 0.4,
    fill: false
  }, {
    label: 'Cash Flow (Grey)',
    data: [1000, -500, 0, 1500, -800, 0, 2000, -1000, 0, 500],
    backgroundColor: 'rgba(128, 128, 128, 0.7)', // Grey color
    yAxisID: 'y2',
    type: 'bar'
  }]
};

const config = {
  type: 'bar',
  data: data,
  options: {
    responsive: true,
    interaction: {
      mode: 'index',
      intersect: false,
    },
    scales: {
      y1: {
        type: 'linear',
        display: true,
        position: 'left',
        title: {
          display: true,
          text: 'KiwiSaver Balance ($)'
        },
        grid: {
          drawOnChartArea: false, // only want the grid lines for the main scale
        },
      },
      y2: {
        type: 'linear',
        display: true,
        position: 'right',
        title: {
          display: true,
          text: 'Cash Flow ($)'
        },
        // grid line settings
        grid: {
          drawOnChartArea: true, // only want the grid lines for the cash flow scale
        },
      },
    },
    plugins: {
      title: {
        display: true,
        text: 'KiwiSaver Portfolio: Long-Term Growth vs. Occasional Cash Flow'
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            let label = context.dataset.label || '';
            if (label) {
              label += ': ';
            }
            if (context.parsed.y !== null) {
              label += new Intl.NumberFormat('en-US', { style: 'currency', currency: 'NZD'...