【问题标题】:Chart.js - displaying multiple line charts using multiple labelsChart.js - 使用多个标签显示多个折线图
【发布时间】:2018-03-26 10:49:52
【问题描述】:

我需要使用 Chart.js 绘制一个有 2 条线的图表。
此行中的每一行都有不同的标签集。
IE。 图一:

1 -> 2  
2 -> 4   
3 -> 8  
4 -> 16

图表2:

1 -> 3  
3 -> 4  
4 -> 6  
6 -> 9

以下示例显然不起作用,因为它使用了 chart1 中的标签。但是有可能用 Chart.js 实现吗?

    var config = {
        type: 'line',
        data: {
            labels: [1,2,3,4,5],
            datasets: [{
                label: 'Chart 1',
                data: [2,4,8,16],
            }, {
                label: 'Chart 2',
                data: [3,4,6,9],
            }]
        },

其他图表库提供了一个(标签/数据)集作为参数,所以我可以简单地给出一个元组作为参数
(即 [(1->2),(2->4),(3->8)...]
对于每个图表,lib 将匹配所有内容。

谢谢

编辑:根据要求提供详细示例:

var config = {
  type: 'line',
  data: {
    labels: [1, 2, 3, 4, 5],
    datasets: [{
      label: 'Chart 1',
      data: [2, 4, 8, 16],
    }, {
      label: 'Chart 2',
      data: [3, 4, 6, 9],
    }]
  },
  options: {
    spanGaps: true,
    responsive: true,
    title: {
      display: true,
      text: 'Chart.js Line Chart'
    },
    tooltips: {
      mode: 'index',
      intersect: false,
    },
    hover: {
      mode: 'nearest',
      intersect: true
    },
    scales: {
      xAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Labels'
        }
      }],
      yAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Values'
        },
        ticks: {
          min: 1,
          max: 10,

        }
      }]
    }
  }
};

window.onload = function() {
  var ctx = document.getElementById('canvas').getContext('2d');
  window.myLine = new Chart(ctx, config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>

<div style="width:90%;" class="container">
  <canvas id="canvas"></canvas><br>
</div>

【问题讨论】:

  • 请提供一个工作示例。你见过 ChartJS 中的exampe about multiaxis 吗?
  • 我添加了一个完整的 html 示例。如前所述,此图表不代表所需的数据,因为它使用相同的标签。 Multiaxes 示例显示了多 Y 轴的示例,但不显示 X 轴上的多数据
  • @MikeNathas,你看到我的回答了吗?

标签: chart.js labels linechart


【解决方案1】:

使用scatter 类型图表和showLine: true 而不是带有标签的line 类型:

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
        }
      }]
    },
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>

【讨论】:

    【解决方案2】:

    这段代码的作用是,它使用chart.js显示多线图

    为标记 x 和 y 值创建一个类

    //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; }
    
    
    }
    

    用于检索数据的控制器代码

      List<LabelPoint> dataPoints = GetProducts.ToList()
                 .GroupBy(p => p.ProductName,
                (k, c) => new LabelPoint()
                {
                    DataPoint = new DataPoint { X = c.Select(y => y.Date.ToString("dd/MM/yyyy HH:mm")).ToList(), Y = c.Select(cs => cs.Quantity).ToList() },
                    Label = k
                }
               ).ToList();
    
            ViewBag.DataPoints = dataPoints;
    

    显示图表和检索数据的cshtml代码

    <canvas id="myChart"></canvas>
    
    
    
    
    <script>
        $(document).ready(function () {
            // Get the data from the controller using viewbag
            // so the data looks something like this   [ { Label : "ABC" , DataPoint :[ { X: '222' , Y :60 } ] } ]
            var data = @Html.Raw(Json.Encode(ViewBag.DataPoints));
            // declare empty array
            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(qtyInLocations.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) ];
            // get the 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;
    }
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多