2015-07-21 84 views
1

我使用chart.js之2.0的静态规模,有时我有一系列走“出规模”等这个/这些系列都没有在图表上可见。所以我决定有固定比例。我关于文件中找到:Chartjs 2.0α,如何对y轴

// 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

在选项> 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/

+0

2015-09-25之后没有“覆盖”。不知道为什么... – Soli

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

+0

这对Chart.js v2.6是否仍然有效?试图让它为我工作没有成功.. – Devl11