gpt4 book ai didi

dataset - 添加数据集条形图-Chart.JS

转载 作者:行者123 更新时间:2023-12-04 09:58:20 24 4
gpt4 key购买 nike

我正在尝试在chart.js中制作条形图(使用chart.js 2.2.2)

我在尝试将新数据集放入图表时遇到麻烦

我如何放置带有数据的新数据集“Vendas”:[10,20,30,40,50,60,70]

var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Compras",
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1,
data: [65, 59, 80, 81, 56, 55, 40],
}
]
};
var ctx = $("#barOrgaoAno").get(0).getContext("2d");
var myBarChart = new Chart(ctx,{
type: "bar",
data: data,
});

我试过两个例子,但都无法正常工作

范例1
barChartDemo.addData([dData()], "dD " + index);

范例2

JSFLiddle
var myNewDataset = {
label: "My Second dataset",
fillColor: "rgba(187,205,151,0.5)",
strokeColor: "rgba(187,205,151,0.8)",
highlightFill: "rgba(187,205,151,0.75)",
highlightStroke: "rgba(187,205,151,1)",
data: [48, 40, 19, 86, 27, 90, 28]
}

var bars = []
myNewDataset.data.forEach(function (value, i) {
bars.push(new myBarChart.BarClass({
value: value,
label: myBarChart.datasets[0].bars[i].label,
x: myBarChart.scale.calculateBarX(myBarChart.datasets.length + 1, myBarChart.datasets.length, i),
y: myBarChart.scale.endPoint,
width: myBarChart.scale.calculateBarWidth(myBarChart.datasets.length + 1),
base: myBarChart.scale.endPoint,
strokeColor: myNewDataset.strokeColor,
fillColor: myNewDataset.fillColor
}))
})

myBarChart.datasets.push({
bars: bars
})

myBarChart.update();

最佳答案

由于您将图表数据存储在变量中(在代码中称为data),因此可以通过按钮上的简单函数来完成此操作:

$('button').click(function() {
// You create the new dataset `Vendas` with new data and color to differentiate
var newDataset = {
label: "Vendas",
backgroundColor: 'rgba(99, 255, 132, 0.2)',
borderColor: 'rgba(99, 255, 132, 1)',
borderWidth: 1,
data: [10, 20, 30, 40, 50, 60, 70],
}

// You add the newly created dataset to the list of `data`
data.datasets.push(newDataset);

// You update the chart to take into account the new dataset
myBarChart.update();
});

您可以看到完整的代码 on this jsFiddle,这是单击后的结果:

enter image description here

关于dataset - 添加数据集条形图-Chart.JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475891/

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