ChartJS Line Chart

Multiple Line Chart

by Seetpal Singh

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<body>
  <div id="chartWrapper">
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
  </div>
</body>

CSS

#chartWrapper {
  border: 1px solid grey;
  padding: 10px;
  border-radius: 4px;
}

canvas {
  background-color: #eee;
}

JavaScript

const plugin = {
  id: 'custom_canvas_background_color',
  beforeDraw: (chart) => {
    const ctx = chart.canvas.getContext('2d');
    ctx.save();
    ctx.globalCompositeOperation = 'destination-over';
    ctx.fillStyle = 'white';
    ctx.fillRect(0, 0, chart.width, chart.height);
    ctx.restore();
  }
};
//To create some padding at bottom of legend
const legendMargin = {
  id: 'legendMargin',
  beforeInit (chart, legend, options) {
    console.log(chart.legend.fit)
    const fitValue = chart.legend.fit;

    chart.legend.fit = function fit () {
      fitValue.bind(chart.legend)();
      return this.height += 20
    }
  }
};

const options = {
  type: 'bar',
  //pointStyle: 'circle',
  plugins: [plugin],
  data: {
    labels: ['2016', '2017', '2018', '2019', '2020', '2021'],
    datasets: [{
      label: 'Newspaper circulation (in millions)',
      data: [2.25, 2.75, 3.25, 3.5, 3.75, 4.25],
      //borderColor: 'pink',
      backgroundColor: '#a1d7e1',
      hoverBackgroundColor: '#2d9bb1',
      yAxisID: 'y',
      order: 1,

    },
    {
      label: 'Global social media users (in billions)',
      data: [500.31, 490.87, 458.26, 430.42, 63.04, 473.52],
      borderColor: '#e4a429',
      backgroundColor: '#e4a429',
      yAxisID: 'y2',
      type: 'line',

    }
    ]
  },
  options: {
    responsive: true,
    plugins: {
      legend: {
        //	https://www.chartjs.org/docs/latest/configuration/legend.html
        display: true,
        //position the legend top left
        position: 'top',
        align: 'start',
        labels: {
          usePointStyle: true,
          boxWidth: 9,
          color: '#212121',
          font: {
            family: 'sans-serif',
            size: 10,
            color: '#212121',
            //weight: '700',
          }
        }
      },
      title: {
        display: true,
        //position the title top left
        position: 'top',
        align: 'start',
        text: '   Social media feast, news famine',
       ...