Chartjs-ChartJS adding shadow color to grid and custom x-axis labels

0👍

For both requirements you can write custom inline plugins.

Example:

var options = {
  type: 'scatter',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [{
          x: 0.25,
          y: 80
        },
        {
          x: 0.75,
          y: -14
        },
        {
          x: 1.25,
          y: -46
        },
        {
          x: 1.75,
          y: 30
        },
        {
          x: 2.25,
          y: 14
        },
        {
          x: 2.75,
          y: -20
        },
        {
          x: 3.25,
          y: -72
        },
        {
          x: 3.75,
          y: -56
        },
        {
          x: 4.25,
          y: -24
        },
        {
          x: 4.75,
          y: -52
        }
      ],
      borderWidth: 1
    }]
  },
  options: {
    plugins: {
        customText: {
        text: ['hi', 'this', 'is', 'text', 'in', 'Mid', '!', ':)'],
        size: '20px',
        color: 'red',
        font: 'Arial black'
      },
      backgrounds: {
        hbars: [{
            from: -28,
            to: -80,
            color: "rgb(195, 230, 195)"
          },
          {
            from: 20,
            to: 28,
            color: "rgb(230, 220, 195)"
          },
          {
            from: 0,
            to: 20,
            color: "rgb(230, 195, 195)"
          }
        ]
      }
    }
  },
  plugins: [{
    id: 'backgrounds',
    beforeDraw: (chart, args, options) => {
      const {
        ctx,
        chartArea,
        scales
      } = chart;
      const y = scales['y-axis-1'];
      const x = scales['y-axis-1'];

      options.hbars.forEach((hBar) => {
        ctx.save();
        ctx.fillStyle = hBar.color;
        ctx.fillRect(chartArea.left, y.getPixelForValue(hBar.from), chartArea.right - chartArea.left, y.getPixelForValue(hBar.to) - y.getPixelForValue(hBar.from));
        ctx.restore();
      })
    }
  },
  {
    id: 'customText',
    afterDraw: (chart, args, options) => {
        const {
        ctx,
        chartArea,
        scales
      } = chart;
      const y = scales['y-axis-1'];
      const x = scales['x-axis-1'];
    
        options.text.forEach((text, i) => {
        ctx.save();
        ctx.textAlign = 'center';
        ctx.font = `${options.size || '20px'} ${options.font || 'Arial'}`;
        ctx.fillStyle = options.color || 'black'
        ctx.fillText(text, x.getPixelForValue((Number(x.ticks[0]) + Number(x.ticks[1])) / 2), y.getPixelForValue((Number(y.ticks[i]) + Number(y.ticks[i + 1])) / 2))

        ctx.restore();
      })
    }
  }]
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
</body>

Leave a comment