Chartjs-Space between start and end of axis

0👍

One way of solving this is to set offset to true on the xAxis and max value on the yAxis‘s ticks configuration.

const data = [100036, 140000, 400000, 900000, 1000000, null];
var options = {
  scales: {
    xAxes: [
      {
        offset: true
      }
    ],
    yAxes: [
      {
        ticks: {
          max: Math.max(...data) * 1.2
        }
      }
    ]
  }
};

Taken from the official docs:

  • If offset is true, extra space is added to the both edges and the axis is scaled
    to fit into the chart area.

  • As for max, setting it will override the maximum number for the scale which by default is derived from the maximum value of the data set.


var ctx = document.getElementById("myChart").getContext("2d");
const data = [100036, 140000, 400000, 900000, 1000000, null];
var myChart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ["1989", "2004", "2014", "2017", "2019", ""],
    datasets: [
      {
        label: "Valorisation",
        data: data,
        backgroundColor: "white",
        borderColor: "rgb(255, 178, 0)",
        borderWidth: 5,
        pointHitRadius: 100
      }
    ]
  },
  options: {
    tooltips: {
      enabled: false
    },
    plugins: {
      datalabels: {
        backgroundColor: "#ffa100",
        padding: 8,
        borderRadius: 6,
        clip: true,
        color: "white",
        font: {
          weight: "bold"
        },
        align: "center",
        offset: 10,
        formatter: function(value) {
          return value.toLocaleString() + " €";
        }
      }
    },
    legend: {
      display: false
    },
    scales: {
      xAxes: [
        {
          offset: true,
          gridLines: {
            display: false
          }
        }
      ],
      yAxes: [
        {
          gridLines: {
            display: false
          },
          ticks: {
            beginAtZero: true,
            min: 0,
            max: Math.max(...data) * 1.2,
            callback: function(value, inde0x, values) {
              return value.toLocaleString() + " €";
            }
          }
        }
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.5.0/dist/chartjs-plugin-datalabels.min.js"></script>
<canvas id="myChart" width="300" height="100"></canvas>

Leave a comment