[Chartjs]-How to make fixed width of column without ticks.min/max in chart.js?

2👍

If I’ve understood your question correctly then the below snippet achieves the result you want.

From two input parameters (width and count of points) it adjusts the right padding of the chart to keep the points at the specified width, regardless of whether there are too many or too few points to fill the width of the canvas.

For demonstration purposes you can change the input values and press the “Update” button to see the result.

let chart = new Chart(document.getElementById("chart"), {
  type: "line",
  data: {
    datasets: [{
      data: []
    }]
  },
  options: {
    maintainAspectRatio: false,
    legend: {
      display: false
    },
    scales: {
      xAxes: [{
        type: 'category',
        gridLines: {
          offsetGridLines: true,
          color: 'orange',
          tickMarkLength: 0,
          drawBorder: false
        },
        ticks: {
          display: false,
          maxRotation: 0,
          beginAtZero: true,
          autoSkip: false,
          stepSize: 1
        },
        offset: true
      }],
      yAxes: [{
        display: false
      }]
    }
  },
  plugins: [{
    resize: function(chart) {
      update(chart);
    }
  }]
});

function update(chart) {
  let pointWidth = parseInt(document.getElementById("pw").value),
    pointCount = parseInt(document.getElementById("pc").value),
    width = chart.width - chart.chartArea.left,
    points = Math.floor(width / pointWidth);

  if (points > pointCount) {
    points = pointCount;
  }

  chart.config.data.labels = _.range(1, points + 1);
  chart.config.data.datasets[0].data = Array.from(Array(points), () => _.random(-5000, 8000));
  chart.options.layout.padding.right = width - (pointWidth * points);

  chart.update();
}

document.getElementById("update").addEventListener("click", function() {
  update(chart);
});
canvas {
  background-color: #f5f5f5
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<p>
  Width: <input id="pw" type="text" value="50">px Count: <input id="pc" type="text" value="5"><button id="update">Update</button>
</p>
<canvas id="chart"></canvas>

Leave a comment