Change the Y-axis values from real numbers to integers in Chart.js

后端 未结 6 1101
忘了有多久
忘了有多久 2020-12-24 04:39

I have a chart that I want to include in my website using Chart.js. In the Y-axis, it gives me real numbers instead of integers. How can I change the number to integers?

相关标签:
6条回答
  • 2020-12-24 05:11

    Check the Chart.js documentation, in the Global configuration section:

    // Boolean - Whether the scale should stick to integers, not floats even if drawing space is there scaleIntegersOnly: true,

    0 讨论(0)
  • 2020-12-24 05:13

    I wasn't able to get the existing answers to work for me when using the new version 2 of Chart.js, so here's what I found to solve this problem in V2:

    new Chart(ctx, {type: 'bar', data: barChartData,
      options:{ 
        scales: {
          yAxes: [{
            ticks: {
              stepSize: 1
            }
          }]
        }
      }
    });
    
    0 讨论(0)
  • 2020-12-24 05:15

    If you like to start in a different number than zero, you have to take that into account:

    var step  = 5;
    var max   = 90
    var start = 40;
    new Chart(income).Bar(barData, {
        scaleOverride: true,
        scaleSteps: Math.ceil((max-start)/step),
        scaleStepWidth: step,
        scaleStartValue: start
    });
    
    0 讨论(0)
  • 2020-12-24 05:21

    Try this, where max is the highest value of your data.

    var steps = 3;
    new Chart(ctx).Bar(plotData, {
        scaleOverride: true,
        scaleSteps: steps,
        scaleStepWidth: Math.ceil(max / steps),
        scaleStartValue: 0
    });
    
    0 讨论(0)
  • 2020-12-24 05:24

    I handled it this way in new version:

    new Chart(ctx, {
      type: 'bar',
      data: chartData,
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true,
              callback: function(value) {if (value % 1 === 0) {return value;}}
            }
          }]
        }
      }
    });
    
    0 讨论(0)
  • 2020-12-24 05:26

    I know this is an old question now, but in the current version (v2.9.3) you can just set the precision of the y-axis ticks to zero to get integers:

    options: {  
        scales: {
            yAxes: [{
                ticks: {
                    precision: 0
                }
            }]
        }
    }
    
    0 讨论(0)
提交回复
热议问题