[Chartjs]-Chart.js: How do I increase the gap between lines in a multiline chart?

2👍

You can make the visual area of the graph bigger, increasing the size of the Chart with CSS if possible. if that is not possible, you could:

  1. move the legend to the side,

     plugins: {
         legend: {
             position: 'right',
         }
     },
    
  2. Make the labels for the x-Axis shorter, since it is a datetime the best way would be setting the x-axis to type time (but you would have to add some libraies, checkout the documentation )

Here a demo, how I would do this:

const data = {
    labels: ['2023-01-01 00:00:00','2023-01-01 01:00:00','2023-01-01 02:00:00','2023-01-01 03:00:00','2023-01-01 05:00:00'], 
    datasets: [{
        label: 'Dataset 1',
        borderColor: '#36A2EB',
        backgroundColor: '#36A2EB',
        data: [50, 150, 180, 160, 10],
     },{
        label: 'Dataset 2',
        borderColor: '#FF6384',
        backgroundColor: '#FF6384',
        data: [20, 110, 80, 190, 20],
     }
     ,{
             label: 'Dataset 3',
        borderColor: '#4BC0C0',
        backgroundColor: '#4BC0C0',
        data: [190, 190, 160, 150, 130],
     }
     ,{
             label: 'Dataset 4',
        borderColor: '#FF9F40',
        backgroundColor: '#FF9F40',
        data: [100, 100, 150, 100, 100],
     }],
};

const config = {
     type: 'line',
    data: data,
    options: {
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: 'right',
            },
        },
         scales: {
            x: {
                type: 'time',
            }
        }
    }
};

const config1 = {
     type: 'line',
    data: data,
    options: {
        maintainAspectRatio: false,
    }
};

new Chart(
    document.getElementById('chart1'),
    config1
);

new Chart(
    document.getElementById('chart'),
    config
);

new Chart(
    document.getElementById('chart2'),
    config1
);
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.js"></script>     
<script src="//cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="//cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
  
  <h2>Before</h2>
  <div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart1" ></canvas>
</div>


<h2>After<h2>
<div class="chart" style="height:184px; width:350px;">
    <canvas  id="chart" ></canvas>
</div>


<h2>Only changing the CSS height<h2>
<div class="chart" style="height:300px; width:350px;">
    <canvas  id="chart2" ></canvas>
</div>

-1👍

I haven’t worked with chart.js for some time but as far as I can see the height of the two charts is different, so because of that the line gap is so narrow there. Try experimenting with styling so that you can increase the height and I think that the gap will increase as well.

Leave a comment