Boardy
Boardy

Reputation: 36205

Set max value of chart.js bar chart

I am creating a bar chart to show a percentage so I therefore only want the graph to go up to a max value of 100.

I got the following in the options:

    var options = {
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>",
        tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
        maintainAspectRatio: false,
        responsive: true,
        animation: false,
        scaleBeginAtZero: true,
        scales: {
            yAxis: [{
                ticks: {
                    beginAtZero:true,
                    min: 0,
                    max: 100
                }
            }]
        }
    };

When the graph loads, my data contains a value of 100%, but instead of the bar graph yAxis value being 100 its going up to 120.

Upvotes: 2

Views: 8491

Answers (2)

evilReiko
evilReiko

Reputation: 20473

For chart.js v3.x.x, use the below (tested using v3.3.2):

var options = {
    scales: {
        y: {
            suggestedMin: 0,
            suggestedMax: 100
        },
        x: {
            suggestedMin: 0,
            suggestedMax: 100
        }
    }
}

Read: https://www.chartjs.org/docs/3.3.2/axes/#axis-range-settings

Upvotes: 1

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32869

The reason of this not working is merely related to the ChartJS version you are using. Since you are using ChartJS version 1.x, the current scales option will not be applicable for the chart.

You should rather use the following scale options ...

scaleOverride: true,
scaleSteps: 10,
scaleStepWidth: 10,

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var ctx = document.getElementById("canvas").getContext("2d");
var data = {
   labels: ['Jan', 'Feb', 'Mar'],
   datasets: [{
      label: "# of votes",
      fillColor: "#07C",
      data: [50, 80, 200]
   }]
};

var myBarChart = new Chart(ctx).Bar(data, {
   scaleOverride: true,
   scaleSteps: 10, // number of ticks
   scaleStepWidth: 10, // tick interval
   scaleBeginAtZero: true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<canvas id="canvas" width="350" height="200"></canvas>

Upvotes: 1

Related Questions