[我正在尝试使用动态x轴制作Chart.js,并始终将接下来的7个月用作x轴的刻度。
但是我有两个问题:
这是我在绘画中制作的示例,以显示我要实现的目标:
这是我到目前为止的代码:
/* Build the charts */
var ctx = document.getElementById('ROIchart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
datasets: [{
label: 'Paid Search and Leads',
backgroundColor: 'red',
borderColor: 'red',
data: [10, 10, 10, 10, 10, 10, 10],
}, {
label: 'SEO and Content',
backgroundColor: 'green',
borderColor: 'green',
data: [0, 2, 8, 21, 57, 77, 100],
fill: true,
}]
},
// Configuration options go here
options: {
responsive: true,
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="ROIchart"></canvas>
使用moment.js库,您可以查看数组的长度,并从开始的月份生成月份,然后将其作为标签使用
/* Build the charts */
var ctx = document.getElementById('ROIchart').getContext('2d');
var array1 = [10, 10, 10, 10, 10, 10, 10];
var months = []
for (let i = 0; i < array1.length; i++) {
months.push(moment().year(2020).month(i + 3).date(0).startOf('month'))
}
var data = {
labels: months,
datasets: [{
label: "Paid Search and Leads",
backgroundColor: 'red',
borderColor: 'red',
data: array1
}, {
label: 'SEO and Content',
backgroundColor: 'green',
borderColor: 'green',
data: [0, 2, 8, 21, 57, 77, 100]
}]
};
var options = {
scales: {
xAxes: [{
type: 'time',
gridLines: {
display: true
},
time: {
minUnit: 'month'
}
}]
}
};
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<canvas id="ROIchart"></canvas>