显示两个折线图,数据从不同点开始

时间:2018-08-29 00:52:05

标签: javascript jquery chart.js

我有两个带有共享标签的数据集,但是一个数据集小于另一个。

例如:

label1: ['8-20', '8-21', '8-22', '8-23']
data1: [100, 120, 150, 170, 150]

label2: ['8-22', '8-23']
data2: [100, 120]

我想显示包含两个数据集的折线图,但是要在适当的刻度线开始第二个数据集,而不是从与data2相同的刻度线开始data1

这可能吗?

var thisChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: label1,
    datasets: [{ 
        data: data1,
        label: "LT15",
        borderColor: gradientStroke,
        backgroundColor: 'rgba(62, 205, 190, 0.1)',
        fill: true,
        spanGaps: true,
        tension: .2,
        borderWidth: 2,
      },{ 
        data: data2,
        label: "LT121",
        borderColor: gradientStroke2,
        backgroundColor: 'rgba(62, 149, 205, 0.2)',
        borderWidth: 2,
        fill: true,
        tension: .2,
        spanGaps: true
      }
    ]
  },
  options: {
    title: {
      display: false,
      text: 'Comparison'
    },
    responsive: true,
    maintainAspectRatio: false,
    legend: {
        lineWidth: 0,
    },
  }
});

1 个答案:

答案 0 :(得分:1)

您只需要用data2填充null,即:

data2: [null, null, 100, 120]

var label1 = ['8-20', '8-21', '8-22', '8-23'],
  data1 = [100, 120, 150, 170, 150],

  label2 = ['8-22', '8-23'],
  data2 = [null, null, 100, 120],

  gradientStroke = 'red',
  gradientStroke2 = 'blue',

  thisChart = new Chart(document.getElementById('chart'), {
    type: 'line',
    data: {
      labels: label1,
      datasets: [{
        data: data1,
        label: "LT15",
        borderColor: gradientStroke,
        backgroundColor: 'rgba(62, 205, 190, 0.1)',
        fill: true,
        spanGaps: true,
        tension: .2,
        borderWidth: 2,
      }, {
        data: data2,
        label: "LT121",
        borderColor: gradientStroke2,
        backgroundColor: 'rgba(62, 149, 205, 0.2)',
        borderWidth: 2,
        fill: true,
        tension: .2,
        spanGaps: true
      }]
    },
    options: {
      title: {
        display: false,
        text: 'Comparison'
      },
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        lineWidth: 0,
      },
    }
  });
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="chart"></canvas>