chart.jschart.js2chart.js3

Chart.js how to use scriptable options


I am migrating chart.js to 3.x as per the migration guide.
https://www.chartjs.org/docs/master/getting-started/v3-migration/

I am trying to set the xAxis zeroLineColor to "#FFFFFF" and I want to have the Grid line color as "#00FFFF" but as per the chart.js migration document document scales.[x/y]Axes.zeroLine* options of axes were removed. Use scriptable scale options instead.

I am not sure how to use scriptable scale options for setting the xAxis line zero to white.

Update:
Working example:
https://jsfiddle.net/g4vq7o2b/2/


Solution

  • In order to obtain different colors for the grid's zero line, you could define an array of colors for the option gridLines.color.

    gridLines: {
      drawBorder: false,
      color: ["#FFFFFF", "#00FFFF", "#00FFFF", "#00FFFF", "#00FFFF"]
    }
    

    Since gridLines.color is a scriptable options, it also accepts a function which is invoked with a context argument for each of the underlying data values as follows:

    gridLines: {
      drawBorder: false,
      color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
    }
    

    Please take a look at below runnable code and see how it works.

    new Chart(document.getElementById("myChart"), {
      type: "line",
      data: {
        labels: ["January", "February", "March", "April", "May", "June", "July"],
        datasets: [{
          label: "My Dataset",
          data: [2, 3, 1, 4, 2, 4, 2],
          fill: false,
          backgroundColor: "rgba(0, 255, 0, 0.3)",
          borderColor: "rgb(0, 255, 0)"
        }]
      },
      options: {
        scales: {
          y: {
            min: 0,
            ticks: {
              stepSize: 1
            },
            gridLines: {
              drawBorder: false,
              color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
            }
          },
          x: {
            gridLines: {
              drawBorder: false,
              color: context => context.tick.value == 0 ? "#FFFFFF" : "#00FFFF"
            }
          }
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.0-beta/chart.min.js"></script>
    <canvas id="myChart" height="90"></canvas>