2015-07-21 52 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