gpt4 book ai didi

asp.net-mvc - 将动态数据集添加到 chart.js

转载 作者:行者123 更新时间:2023-12-04 00:36:15 25 4
gpt4 key购买 nike

我正在尝试向 chart.js 图表动态添加线条,但我不知道我有多少数据集我已经为此苦恼了两天了......

我有一个包含年、月和值的列表:

    public int Month { get; set; }
public int Year { get; set; }
public int Value { get; set; }

我的 HTML 只是图表的 Canvas :

<div>
<canvas id="myChart"> </canvas>
</div>

我像这样填充图表:

 var dataList = [];
var lableList = [];
@foreach (var dataInput in Model.TurnoverByReservation)
{

@:dataList.push("@dataInput.Value");
@:lableList.push("@dataInput.MonthName");
}

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: lableList,
datasets: [
{
label: 'Booking value',
data: dataList,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
callback: function(value, index, values) {
if (parseInt(value) >= 1000) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return value;
}
}
}
}
]
}
}
});

所以问题是;我怎样才能将不同的数据集添加到图表中,以便我可以使用这样的东西?

@foreach (var year in Model.TurnoverByReservation.OrderBy(x =>x.Month).GroupBy(x => x.Year))
{
foreach (var value in year)
{
//Add the value to the dataset, somehow...
}
}

最佳答案

您可以随时填充数据集数组,即使在通过编辑存储在 myChart.config 中的数组 datasets 调用 new Chart() 函数之后也是如此。数据.

假设您从查询中得到类似的结果

var model = {
2015: [20, 12, 32, 8, 25, 14, 20, 12, 32, 8, 25, 14],
2016: [17, 26, 21, 41, 8, 23, 17, 26, 21, 41, 8, 23],
2017: [23, 15, 8, 24, 38, 20, 23, 15, 8, 24, 38, 20]
};

你循环进入它,并将你拥有的每一个数据存储在你的新数据集中:

// For every year in your data ...
for (year in model) {
// You create a new dataset with empty values and the year as the label
var newDataset = {
label: year,
data: []
};

// For every value for this specific year ..
for (value in model[year]) {
// You populate the newly created dataset
newDataset.data.push(model[year][value]);
}

// Then you add the dataset to the charts' ones
myChart.config.data.datasets.push(newDataset);
}

// Finally, make sure you update your chart, to get the result on your screen
myChart.update();

确保您至少使用以下内容启动您的图表:

var myChart = new Chart(ctx, {
type: 'line',
data: {
// You need as much labels as the number of values you have
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
// This makes sure you'll get something with `myChart.config.data.datasets`
datasets: []
}
});

如果您的模型结构不同,您仍然应该能够稍微更改循环以使其正常工作。

您可以在 this fiddle 中使用默认数据检查结果.

关于asp.net-mvc - 将动态数据集添加到 chart.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805180/

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