Chartjs-Is there a way to create a chart with only a single axis?

0👍

This is straightforward to achieve through styling a line chart appropriately and using linear x- & y-axes with points defined via x and y coordinates.

By keeping y at 0 you can assure the points all appear in the same horizontal position.

The example below gets the visual result you want, but you’ll probably want to disable tooltips for the ‘fake’ x-axis line via a callback:

let range = {
    min: 0,
    max: 100
  },
  pointVal = 65;

new Chart(document.getElementById("chart"), {
  type: "line",
  data: {
    labels: ["", "", ""],
    datasets: [{
      pointBackgroundColor: "green",
      pointRadius: 10,
      pointHoverRadius: 10,
      pointStyle: "rectRot",
      data: [{
        x: pointVal,
        y: 0
      }]
    }, {
      // this dataset becomes the 'fake' x-axis line.
      pointBackgroundColor: "black",
      borderColor: "black",
      data: [{
          x: range.min,
          y: 0
        },
        {
          x: range.max / 2,
          y: 0
        },
        {
          x: range.max,
          y: 0
        }
      ]
    }]
  },
  options: {
    legend: {
      display: false
    },
    hover: {
      mode: "point"
    },

    layout: {
      padding: {
        left: 10,
        right: 10,
        top: 0,
        bottom: 0
      }
    },
    scales: {
      xAxes: [{
        type: "linear",
        display: false
      }],
      yAxes: [{
        display: false
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<div style="width:200px">
  <canvas id="chart"></canvas>
</div>

Leave a comment