Chartjs 2.0 alpha,如何为y轴设置静态比例

时间:2015-07-21 10:51:06

标签: linechart chart.js

我正在使用Chart.js 2.0,有时我的系列会超出"超出规模"所以这个/这些系列在图表上是不可见的。所以我决定有固定的比例。我在文档上找到了:

// Object - if specified, allows the user to override the step generation algorithm.
//          Contains the following values
//              start: // number to start at
//              stepWidth: // size of step
//              steps: // number of steps

我试过了:

{
 type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
 display: true,
 position: "right",
 id: "y-axis-2",
  // grid line settings
 gridLines: {
      show: true,
      ( ... ) 
 },

object:{
    start: 0,       // number to start at
    stepWidth: 50,  // size of step
    steps: 5,       // number of steps
},
// label settings
 labels: {
      show: true,
      ( ... )
 }
}

但是y轴-2没有固定的比例。我应该在哪里/如何放置这3个代码行?

2 个答案:

答案 0 :(得分:8)

Chart.js已删除v2.0中的覆盖功能(#1564),并将其替换为自定义缩放类型和回调。不幸的是,目前还没有关于这方面的文档,但我已经根据线性标度整理了一些似乎有用的东西。

var UserDefinedScaleDefaults = Chart.scaleService.getScaleDefaults("linear");
var UserDefinedScale = Chart.scaleService.getScaleConstructor("linear").extend({
  buildTicks: function() {
    this.min = this.options.ticks.min;
    this.max = this.options.ticks.max;
    var stepWidth = this.options.ticks.stepWidth;

    this.ticks = [];
    for (var tickValue = this.min; tickValue <= this.max; tickValue += stepWidth) {
      this.ticks.push(tickValue);
    }

    if (this.options.position == "left" || this.options.position == "right") {
      this.ticks.reverse();
    }

    if (this.options.ticks.reverse) {
      this.ticks.reverse();
      this.start = this.max;
      this.end = this.min;
    } else {
      this.start = this.min;
      this.end = this.max;
    }

    this.zeroLineIndex = this.ticks.indexOf(0);
  }
});

Chart.scaleService.registerScaleType("user-defined", UserDefinedScale, UserDefinedScaleDefaults);

然后您可以使用“用户定义”类型并在选项中指定刻度:

var config = {
  type: 'line',
  data: { datasets: [{data: data}] },
  options: {
    scales: {
      xAxes: [{
        type: "linear",
        position: "bottom"
      }],
      yAxes: [{
        type: "user-defined",
        ticks: {
          min: 0,
          max: 10,
          stepWidth: 2
        }
      }]
    }
  }
};

此处要覆盖的关键功能是buildTicks,它指定this.minthis.maxthis.startthis.endthis.zeroLineIndex和数组实际刻度值this.ticks

Codepen example

答案 1 :(得分:2)

在选项&gt;下yAxes

var ctx = document.getElementById("chart").getContext("2d");
var myChart = new Chart(ctx, {
    type: "line",
    data: lineChartData,
    options: {
        scales: {
            yAxes: [{
                override: {
                    stepWidth: 20,
                    start: 0,
                    steps: 10
                }
            }]
        }
    }
});

小提琴 - https://jsfiddle.net/es83ujat/