将动态数据集添加到chart.js

时间:2017-01-23 11:21:52

标签: asp.net-mvc chart.js

我正在尝试动态添加行到chart.js图表​​,我不知道有多少数据集 我已经被这两天撞了过头......

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

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

我的HTML只是图表的画布:

<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...
 }
}

2 个答案:

答案 0 :(得分:4)

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

假设您从查询中得到类似的内容

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中的默认数据检查结果。

答案 1 :(得分:2)

这是最终的解决方案,非常感谢@tektiv的所有帮助

var borderColors = [
    '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)'
];
var backgroundColors = [
    '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)'
];
        var ctx = document.getElementById("myChart");
    var myChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
            label: "#value",
            datasets: []
        },
        options: {
            scales: {
                yAxes: [
                    {
                        ticks: {
                            beginAtZero: true
                        }
                    }
                ]
            }
        }
    });

    @{StringBuilder valueObj = new StringBuilder();}

    var objModel = new Object();

    var myArray = [];
    @foreach (var years in Model.TurnoverByReservation.OrderBy(x => x.Month).GroupBy(x => x.Year))
    {
        foreach (var value in years)
        {
            @:myArray.push("@value.Value");
        }
        @:objModel["@years.Key"] = myArray;
        @:myArray = [];
    }

    var colorInt = 0; //Used to set a variable background and border color

    for (year in objModel) {
        // You create a new dataset with empty values and the year as the label
        var newDataset = {
            label: year,
            data: [],
            backgroundColor: backgroundColors[colorInt],
            borderColor:borderColors[colorInt]
        };
        colorInt += 1;
        // For every value for this specific year ..
        for (value in objModel[year]) {
            // You populate the newly created dataset
            newDataset.data.push(objModel[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();