javascript - 如何在 x 轴上制作带有动态月份的 Chart.js
问题描述
我正在尝试制作一个带有动态 x 轴的 Chart.js,它将始终使用接下来的 7 个月作为 x 轴的刻度。
但我有两个问题:
- 线条没有显示在我的图表上
- 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+1).date(0).startOf('month'))
}
var chart = new Chart(ctx, {
type: 'line',
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],
fill: true,
}]
},
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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
<canvas id="ROIchart"></canvas>
推荐阅读
- ruby-on-rails - Ruby on Rails的includes方法的使用
- sql - 按列分组并在sql上获取最大和最小ID
- curl - 使用 curl 命令时出现 InfluxDB 无效字段格式错误
- java - Android VideoView 我随机收到“无法播放此视频”错误
- python - 使用 Statsmodels MLEmodel 构建自定义状态空间模型
- flutter - 使用 ClipPath 的波浪曲线不平滑
- python - 在 for 循环中使用 udf 在 Pyspark 中创建多个列
- opengl - 如何将 glVertexAttrib3f 与 vao 一起使用?
- python - 来自特定类/枚举的特定类型变量的 Python 类型提示
- c# - WPF - 显示自定义字体的符号时出现问题