繁体   English   中英

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

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

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

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

我已经尝试了几件事,但无济于事。

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

我真的很感激一些帮助! 谢谢。

这是我的小提琴: 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>

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

如果理解正确,您仍然希望在 roiMonth 计算中使用投资月值,因此我创建了“投资月值”,因此只有投资小于投资起始月时才会为空。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM