gpt4 book ai didi

javascript - 更新图表时修改 chart.js 中的标签

转载 作者:行者123 更新时间:2023-11-30 13:44:15 25 4
gpt4 key购买 nike

我正在使用 chart.js 创建一些动态图表。我知道如何创建不同类型的图表并修改我想要显示的数据,但问题是我不知道如何更新标签。

这里我展示了我的代码只是更新数据:

const colores = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850", "#FFF850"];
const etiquetas = ["Africa", "Asia", "Europe", "Latin America", "North America","Miguel"];
var paquetes_pie = null;

function graficoPaquetes(datos) {
let ctx = document.getElementById("paquetes_graf").getContext("2d");
let tipo = 'pie';
let titulo = 'Paquetes perdidos';

paquetes_pie = new Chart(ctx, {
type: tipo,
data: {
labels: etiquetas,
datasets: [{
label: "Paquetes perdidos",
backgroundColor: colores,
borderWidth: 1,
borderColor: '#FFF',
data: datos,
}]
},
options: {
title: {
display: true,
text: titulo
}
}
});
}

function addData(chart, title, data) {
chart.options.title.text = title;
chart.data.datasets.forEach((dataset, i) => {
dataset.data = data;
});
chart.update();
}

$(document).ready(function() {

var data = [2478, 5267, 734, 784, 433, 99];
graficoPaquetes(data);

$('.btn_graf').click(function() {
data = [24, 67, 4, 4, 3, 9];
addData(paquetes_pie, "Paquetes perdidos", data);
});
});

现在我展示一些更新标签的错误思路:

function addData(chart, title, data, etiquetas) {
chart.options.title.text = title;
chart.data.datasets.forEach((dataset, i) => {
dataset.data = data;
});
/*chart.data.forEach((dat, i) => { //first attempt
dat.labels = etiquetas;
});*/
//chart.data.labels = etiquetas; // Second attempt
chart.update();
}

$('.btn_graf').click(function() {
data = [24, 67, 4, 4, 3, 9];
etiquetas = ["A", "B", "C", "D", "E", "F"];
addData(paquetes_pie, "Paquetes perdidos", data, etiquetas);
});

有人可以帮帮我吗?

非常感谢

最佳答案

你可以像下面这样更新

chart.config.data.labels = newLabels // you can pass the new labels
chart.update()

关于javascript - 更新图表时修改 chart.js 中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59611169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com