# 更新图表
¥Updating Charts
在创建图表后想要更新图表是很常见的。当图表数据或选项发生变化时,Chart.js 将根据新的数据值和选项进行动画处理。
¥It's pretty common to want to update charts after they've been created. When the chart data or options are changed, Chart.js will animate to the new data values and options.
# 添加或删除数据
¥Adding or Removing Data
通过更改数据数组来支持添加和删除数据。要添加数据,只需将数据添加到数据数组中,如本示例所示,要删除它,你可以再次弹出它。
¥Adding and removing data is supported by changing the data array. To add data, just add data into the data array as seen in this example, to remove it you can pop it again.
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();
}
# 更新选项
¥Updating Options
要更新选项,支持就地改变 options
属性或传入新的选项对象。
¥To update the options, mutating the options
property in place or passing in a new options object are supported.
如果选项在适当的位置发生变化,其他选项属性将被保留,包括那些由 Chart.js 计算的。
¥If the options are mutated in place, other option properties would be preserved, including those calculated by Chart.js.
如果创建为新对象,则就像使用选项创建新图表一样 - 旧的选项将被丢弃。
¥If created as a new object, it would be like creating a new chart with the options - old options would be discarded.
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();
}
可以在不更改其他选项的情况下单独更新缩放。要更新比例,请传入一个包含所有自定义项(包括未更改的自定义项)的对象。
¥Scales can be updated separately without changing other options. To update the scales, pass in an object containing all the customization including those unchanged ones.
在使用新的 id
或更改后的 type
更新比例后,引用 chart.scales
中任何一个的变量都将丢失。
¥Variables referencing any one from chart.scales
would be lost after updating scales with a new id
or the changed type
.
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 更新特定比例。
¥You can update a specific scale by its id as well.
function updateScale(chart) {
chart.options.scales.y = {
type: 'logarithmic'
};
chart.update();
}
更新选项的代码示例可以在 line-datasets.html (opens new window) 中找到。
¥Code sample for updating options can be found in line-datasets.html (opens new window).
# 防止动画
¥Preventing Animations
有时当图表更新时,你可能不需要动画。为此,你可以使用 'none'
作为模式调用 update
。
¥Sometimes when a chart updates, you may not want an animation. To achieve this you can call update
with 'none'
as mode.
myChart.update('none');