Click here to Skip to main content
15,035,283 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I need to display multiple lines of data on a javascript chart. I successfully display the chart, but for some reason the label just isn't displaying.

I have tried multiple examples but I don't find exactly what I need to do.

What I have tried:

<head>
<script>var chart = new CanvasJS.Chart("chartContainer", {
                title: {
                    text: "Data"
                },
                data: [
                    {
                        label: "Name1",
                        type: "line",
                        dataPoints: [
                            { x: 10, y: 21 },
                            { x: 11, y: 25 },
                            { x: 12, y: 30 }


                        ]
                    },
                    {
                        label: "Name2",
                        type: "line",
                        dataPoints: [
                            { x: 10, y: 31 },
                            { x: 11, y: 20 },
                            { x: 12, y: 15 }

                        ]
                    }
                ]
            });
            chart.render();</script>
</head>

<body>
    <canvas id="canvas"></canvas>
    <div id="chartContainer" style="height: 300px; width: 100%;"></div>
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
Posted
Updated 29-Apr-21 3:21am

I see the following works fine:
JavaScript
var ctx = document.getElementById("myChart");

var myChart = new Chart(ctx, {
  type: 'scatter',
  data: {
    datasets: [
    	{
        label: 'Chart 1',
        data: [{x: 1, y: 2}, {x: 2, y: 4}, {x: 3, y: 8},{x: 4, y: 16}],
        showLine: true,
        fill: false,
        borderColor: 'rgba(0, 200, 0, 1)'
    	},
      {
        label: 'Chart 2',
        data: [{x: 1, y: 3}, {x: 3, y: 4}, {x: 4, y: 6}, {x: 6, y: 9}],
        showLine: true,
        fill: false,
        borderColor: 'rgba(200, 0, 0, 1)'
    	}
    ]
  },
  options: {
    tooltips: {
      mode: 'index',
      intersect: false,
    },
    hover: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    },
  }
});

HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>

Reference: Chart.js - displaying multiple line charts using multiple labels - Stack Overflow[^]
   
For multi line chart in MVC using chart.js (dynamic)

Create a Class LabelPoint, Reference your X and Y points on the graph

so the data looks something like this   [ { Label : "ABC" , DataPoint :[ { X: '222' , Y :60 } ] } ]


It will be an array of object, in that object there will be an array of object.

ASP.NET


//DataContract for Serializing Data - required to serve in JSON format
	[DataContract]
	public class LabelPoint
	{
		//Explicitly setting the name to be used while serializing to JSON.
		[DataMember(Name = "label")]
		public string Label { get; set; }

		public DataPoint DataPoint { get; set; }
	}
	[DataContract]
	public class DataPoint
	{
		[DataMember(Name = "x")]
		public List<string> X { get; set; }

		//Explicitly setting the name to be used while serializing to JSON.
		[DataMember(Name = "y")]
		public List<string> Y { get; set; }


	}

Controller Code
List dataPoints = detailIM
                     .GroupBy(p => p.Product,
                    (k, c) => new LabelPoint()
                    {
                        DataPoint = new DataPoint { X = c.Select(y => 
                          y.Quantity).ToList(), Y = c.Select(cs => cs.Date).ToList() },
                        Label = k
                    }
                   ).ToList();

                ViewBag.DataPoints = dataPoints;


on your cshtml, retrieve the values

var data = @Html.Raw(Json.Encode(ViewBag.DataPoints));


var dataSet = [];  var qty= []; var dates= [];
       // loop through the data and get the Label as well as get the created dates and qty for the array of object
       for (var i = 0; i < data.length; i++) {

           qty.push(data[i].DataPoint.Y);
           for (var d = 0; d < data[i].DataPoint.X.length; d++) {
               // we're setting this on the X- axis as the  label so we need to make sure that we get all the dates between searched dates
               dates.push(data[i].DataPoint.X[d]);
           }
            // we create an array of object, set the Lable which will display LocationName, The data here is the Quantity
               dataSet.push(
               {
                   label: data[i].Label,
                   data: data[i].DataPoint.Y,
                   fill: false,
                   borderColor: poolColors(qty.length),
                   pointBorderColor: "black",
                   pointBackgroundColor: "white",
                   lineTension: 0.1
               }
           );
       }
       // this is the options to set the Actual label like Date And Quantity
       var options = {
           scales: {
                xAxes: [{
                scaleLabel: {
                display: true,
                labelString: "Date",
                fontSize: 20
                 },
                 }],

           yAxes: [{
               ticks: {
                   beginAtZero:true
               },
               scaleLabel: {
                    display: true,
                    labelString: 'Quantity',
                    fontSize: 20
                }
           }]
           }
       };


// we need to remove all duplicate values from the CreatedDate array
     var uniq = [ ...new Set(dates) ];


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


var ctx = document.getElementById("myChart").getContext('2d');
      // build the chart
      var myChart = new Chart(ctx, {
          type: 'line',
          data: {
              labels: uniq,
              datasets:dataSet
          },
           options: options
      });


    /// will get get random colors each time
    function dynamicColors() {
    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    return "rgba(" + r + "," + g + "," + b + ", 0.5)";
    }

    /// will display random colors each time
    function poolColors(a) {
    var pool = [];
    for(i = 0; i < a; i++) {
        pool.push(dynamicColors());
    }
    return pool;
}
   
Comments
Richard Deeming 29-Apr-21 10:27am
   
The question makes no mention of ASP.NET, MVC or otherwise. And it was already solved last August.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900