# 設定
設定用於更改圖表的行為。有一些屬性可以控制樣式、字體、圖例等等。
# 設定物件結構
Chart.js 設定的頂層結構
const config = {
type: 'line',
data: {},
options: {},
plugins: []
}
# type
圖表類型決定了圖表的主要類型。
注意 數據集可以覆蓋 type
,這就是混合圖表的建構方式。
# data
詳情請參閱數據結構。
# options
大多數文檔都在討論這些選項。
# plugins
內嵌外掛程式可以包含在此陣列中。這是為單個圖表添加外掛程式的另一種方法(相較於全域註冊外掛程式)。有關外掛程式的更多資訊,請參閱開發者章節。
# 全域設定
Chart.js 1.0 中引入了這個概念,以保持設定 DRY (在新視窗開啟),並允許在圖表類型之間全域更改選項,避免需要為每個實例或特定圖表類型的預設指定選項。
Chart.js 會將傳遞給圖表的 options
物件與全域設定合併,並適當地使用圖表類型預設值和比例預設值。這樣一來,您可以在個別圖表設定中盡可能地具體,同時仍然可以更改所有適用圖表類型的預設值。全域通用選項定義於 Chart.defaults
中。每個圖表類型的預設值在該圖表類型的文檔中討論。
以下範例會將所有圖表的互動模式設定為 'nearest',除非圖表類型預設值或在建立時傳遞給建構子的選項覆蓋了此設定。
Chart.defaults.interaction.mode = 'nearest';
// Interaction mode is set to nearest because it was not overridden here
const chartInteractionModeNearest = new Chart(ctx, {
type: 'line',
data: data
});
// This chart would have the interaction mode that was passed in
const chartDifferentInteractionMode = new Chart(ctx, {
type: 'line',
data: data,
options: {
interaction: {
// Overrides the global setting
mode: 'index'
}
}
});
# 數據集設定
選項可以直接在數據集上設定。數據集選項可以在多個不同的層級進行更改。請參閱 選項,以了解如何解析選項的詳細資訊。
以下範例會將所有折線數據集的 showLine
選項設定為 'false',但建立時傳遞給數據集的選項所覆蓋的除外。
// Do not show lines for all datasets by default
Chart.defaults.datasets.line.showLine = false;
// This chart would show a line only for the third dataset
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
data: [0, 0],
}, {
data: [0, 1]
}, {
data: [1, 0],
showLine: true // overrides the `line` dataset default
}, {
type: 'scatter', // 'line' dataset default does not affect this dataset since it's a 'scatter'
data: [1, 1]
}]
}
});