Wells
Wells

Reputation: 65

Custom labeling/fixed range on x-axis in Chart.js for horizontal bar chart?

I'm trying to set a fixed range for a single bar, horizontal bar chart in Chart.JS

The labeling array only works on the vertical axis but I would like to have a fixed set of labels on the X-axis.

Example: https://altonwells.webflow.io/chart-js

var ctx = document.getElementById('SATScoreGraph2').getContext('2d');
var myBarChart = new Chart(ctx, {
  type: 'horizontalBar',
  data: {
    labels: [""],
    datasets: [{
      barThickness: 48,
      barPercentage: 0.7,
      categoryPercentage: 1.0,
      backgroundColor: ["#ff6f47"],
      data: [1480]
    }]
  },
  options: {
    indexAxis: 'x',
    title: {
      display: false,
      text: 'Average SAT Score'
    },
    legend: {
      display: true
    },
    tooltips: {
      enabled: false
    }
  }
});
<html>

<body>
  <canvas id="SATScoreGraph2"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</body>

</html>

Upvotes: 3

Views: 1777

Answers (2)

Pepe Alvarez
Pepe Alvarez

Reputation: 1624

This is what worked for me

options: {
    scales: {
        x: {
            min: 0,
            max: 100,
            display: false,
        },
    }
}

Display equals to false was set since if not it appears another scale bar below the one I had chosen for my data. According to the docs:

min: User defined minimum number for the scale, overrides minimum value from data.

max: User defined maximum number for the scale, overrides maximum value from data.

Upvotes: 0

Wells
Wells

Reputation: 65

ReAd ThE DoCuMEnTaTIoN

https://www.chartjs.org/docs/latest/axes/cartesian/linear.html

options: {
indexAxis: 'x',
  title: {
    display: false,
    text: 'Average SAT Score'
  },
  legend: {
    display: true
  },
   tooltips: {
    enabled: false
  },
  scales: {
        xAxes: [{
            ticks: {
                suggestedMin: 800,
                suggestedMax: 1600
            }
        }]
    }
}

Upvotes: 0

Related Questions