Search code examples
chart.jsreact-chartjs

Chartjs 2 Line Graph Single Stroke Between Datasets


I'm trying to make a line graph with a single stroke between each datapoint on the graph. There should be a small space between each side of the datapoint.

enter image description here

I see that the docs say to use borderDash but the strokes will run through my datapoints instead of only between. I looked for a way to add padding/margin around each datapoint but I don't see a way to do that.


Solution

  • Because of the borderDash limitation that you pointed out, I think the easiest way to get the desired effect is to use a combination of pointRadius, backgroundColor, pointBorderColor, and pointBorderWidth.

    This works by creating a white border around each point that makes it looks like there's a gap.

    For example:

    backgroundColor: '#000',
    pointRadius: 5,
    pointBorderColor: '#fff',
    pointBorderWidth: 3,
    

    Here's what it looks like:

    Chart with borders around point

    And here's a runnable snippet:

    const ctx = document.getElementById('myChart').getContext('2d');
    
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        datasets: [{
          borderColor: '#000',
          backgroundColor: '#000',
          pointRadius: 5,
          pointBorderColor: '#fff',
          pointBorderWidth: 3,
          lineTension: 0,
          data: [6.06, 82.2, -22.11, 21.53, -21.47, 73.61, -53.75, -60.32, -30, 20, 22, 25],
          label: 'Dataset',
          fill: false,
        }, ],
      },
      options: {
        scales: {
          xAxes: [{
            gridLines: {
              drawOnChartArea: false,
              drawTicks: false
            }
          }],
          yAxes: [{
            gridLines: {
              drawOnChartArea: false,
              drawTicks: false
            }
          }]
        },
        legend: {
          display: false
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
    
    <body>
      <canvas id="myChart" width="600" height="400"></canvas>
    </body>