Chart.js Line-Chart with different Labels for each Dataset

前端 未结 3 1589
梦毁少年i
梦毁少年i 2020-12-31 05:37

Using Chart.js you can create line charts and for that you have to privde labels and datasets. for example:

var data = {
    labels: [\"January\", \"February         


        
3条回答
  •  梦毁少年i
    2020-12-31 06:12

    I had a battle with this today too. You need to get a bit more specific with your dataset. In a line chart "datasets" is an array with each element of the array representing a line on your chart. Chart.js is actually really flexible here once you work it out. You can tie a line (a dataset element) to an x-axis and/or a y-axis, each of which you can specify in detail.

    In your case if we stick with a single line on the chart and you want the "time" part of the entry to be along the bottom (the x-axis) then all your times could go into the "labels" array and your "number" would be pin-pointed on the y-axis. To keep it simple without specifying our own scales with x and y axes and given this data:

    var MyData = [{time:"10:00", number: "127"},
                  {time:"11:00", number: "140"},
                  {time:"12:00", number: "135"},
                  {time:"13:00", number: "122"}];
    

    You could set up the "data" property of your chart to be:

    var data = {
        labels: ["10:00", "11:00", "12:00", "13:00"],
        datasets: [
            {
                label: "My First dataset",
    
                // Insert styling, colors etc here
    
                data: [{x: "10:00", y: 127},
                       {x: "11:00", y: 140},
                       {x: "12:00", y: 135},
                       {x: "13:00", y: 122}]
            }
        ]};
    

    Note that the data array is now a bit more specific with each element of data plotting itself on the x-axis by referencing one of the labels rather than just being a raw number. You can now put another dataset object in the datasets array following this pattern and have two lines, obviously give your lines different colours and names ("label").

    Hope this helps.

提交回复
热议问题