# 更新圖表

在圖表建立後,想要更新它們是很常見的需求。當圖表資料或選項變更時,Chart.js 會將動畫套用到新的資料值和選項。

# 新增或移除資料

透過變更資料陣列來支援新增和移除資料。要新增資料,只需將資料新增到資料陣列中,如本範例所示,要移除資料,您可以再次使用 pop() 方法。

function addData(chart, label, newData) {
    chart.data.labels.push(label);
    chart.data.datasets.forEach((dataset) => {
        dataset.data.push(newData);
    });
    chart.update();
}
function removeData(chart) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
        dataset.data.pop();
    });
    chart.update();
}

# 更新選項

要更新選項,支援直接變更 options 屬性或傳遞新的選項物件。

  • 如果直接變更選項,其他選項屬性(包括 Chart.js 計算的屬性)將會保留。
  • 如果建立為新的物件,則就像使用該選項建立新圖表一樣 - 舊選項將被捨棄。
function updateConfigByMutating(chart) {
    chart.options.plugins.title.text = 'new title';
    chart.update();
}
function updateConfigAsNewObject(chart) {
    chart.options = {
        responsive: true,
        plugins: {
            title: {
                display: true,
                text: 'Chart.js'
            }
        },
        scales: {
            x: {
                display: true
            },
            y: {
                display: true
            }
        }
    };
    chart.update();
}

可以單獨更新刻度,而無需變更其他選項。要更新刻度,請傳入包含所有自訂設定的物件,包括未變更的設定。

在以新的 id 或變更的 type 更新刻度後,任何引用 chart.scales 的變數都會遺失。

function updateScales(chart) {
    let xScale = chart.scales.x;
    let yScale = chart.scales.y;
    chart.options.scales = {
        newId: {
            display: true
        },
        y: {
            display: true,
            type: 'logarithmic'
        }
    };
    chart.update();
    // need to update the reference
    xScale = chart.scales.newId;
    yScale = chart.scales.y;
}

您也可以透過其 id 更新特定的刻度。

function updateScale(chart) {
    chart.options.scales.y = {
        type: 'logarithmic'
    };
    chart.update();
}

可以在 line-datasets.html (開啟新視窗) 中找到更新選項的程式碼範例。

# 防止動畫

有時,當圖表更新時,您可能不希望出現動畫。若要達成此目的,您可以將 'none' 作為模式呼叫 update

myChart.update('none');
上次更新時間: 2024/5/17 下午 12:33:38