Chartjs - 使线开始于...但保持 x 轴数据

Chartjs - make line start at ... but maintain x-axis data

我根据一些输入数据创建了一个动态折线图。目的是客户可以通过下拉菜单指示“投资”应该从哪个月开始。

因此,例如,如果“投资”直到第 6 个月才开始,那么该行应该仅从 x 轴上的 6 开始。但其他行“Case”和“ROI”仍应从 1 开始。

我尝试了很多方法但都无济于事。

我尝试根据用户所做的选择更改 x 轴的“最小刻度”,但这会使所有线都从另一个点开始,而不是仅从“投资”线开始。另一个问题是选择之前的每个数字都会从 x 轴上消失。但我真的想保留 1-60 的每个数字,即使用户选择在第 10 个月开始“投资”,例如。

非常感谢您的帮助!谢谢

这是我的 fiddle:https://jsfiddle.net/js5pha24/

var options = {
  type: 'line',
  data: {
    labels: [],
    datasets: [{
      label: 'Case',
      data: [],
      backgroundColor: 'rgba(152,164,135, 0.5)',
      borderColor: 'rgb(152,164,135)',
      fill: false
    }, {
      label: 'Case',
      data: [],
      backgroundColor: 'rgba(145,139,167, 0.5)',
      borderColor: 'rgb(145,139,167)',
      fill: false
    }, {
      label: 'Case',
      data: [],
      backgroundColor: 'rgba(206,157,206, 0.5)',
      borderColor: 'rgb(206,157,206)',
      fill: false
    }]
  },
  options: {
    legend: {
      display: true,
      position: "top"
    },
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true,
          autoSkip: true,
          maxRotation: 0,
          minRotation: 0
        }
      }],
      yAxes: [{
        ticks: {
          callback: value => {
            return "€ " + value;
          }
        }
      }]
    }
  }
}

for (let i = 1; i <= 60; i++) {
  options.data.labels.push(i);

  const caseMonth = 118187 * i;
  options.data.datasets.find(set => set.label === "Case").data.push(caseMonth);

  const investMonth = 500000 + (20000 * i);
  options.data.datasets.find(set => set.label === "Investment").data.push(investMonth);

  const roiMonth = caseMonth - investMonth;
  options.data.datasets.find(set => set.label === "ROI").data.push(roiMonth);
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
canvas { background-color : #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
</body>

您可以在图表数据上放置 null 值,这样一行可以在其他行之后开始。例如,如果您希望投资线从第 10 个月开始,您可以将前十个 investMonth 值替换为 null

如果理解正确,您仍想在 roiMonth 计算中使用 investMonth 值,因此我创建了“investMonthValue”,因此只有小于 investmentStartMonth 的投资才会为空。

let investmentStartMonth = 10

for (let i = 1; i <= 60; i++) {
    options.data.labels.push(i);

  const caseMonth = 118187 * i;
  options.data.datasets.find(set => set.label === "Case").data.push(caseMonth);

  let investMonth = 500000 + (20000 * i);
  let investMonthValue = i<investmentStartMonth?null:investMonth
  options.data.datasets.find(set => set.label === "Investment").data.push(investMonthValue);

  const roiMonth = caseMonth - investMonth;
  options.data.datasets.find(set => set.label === "ROI").data.push(roiMonth);
}