kar*_*thi 3 javascript momentjs chart.js
我正在使用以下代码使用Chart js插件生成折线图,其中我面临的问题是X轴值重复两次。
function newDate(days) {
return moment().add(days, 'd').format('MM/DD');
}
var painChartContext = document.getElementById('pain_chart');
var painChart = new Chart(painChartContext, {
type: 'line',
data: {
labels: [newDate(-7), newDate(-6), newDate(-5), newDate(-4), newDate(-3), newDate(-2), newDate(-1)],
datasets: [{
label: "Pain",
data: [8, 9, 7, 3, 10, 3, 4],
fill: false,
borderColor: '#b71705',
spanGaps: true
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MM/DD',
'second': 'MM/DD',
'minute': 'MM/DD',
'hour': 'MM/DD',
'day': 'MM/DD',
'week': 'MM/DD',
'month': 'MM/DD',
'quarter': 'MM/DD',
'year': 'MM/DD',
},
min: '04/13',
max: '04/19'
}
}],
},
}
});
Run Code Online (Sandbox Code Playgroud)
正如我上面提到的,这为我提供了下图,其中x轴日期值重复了两次。
同样在我的控制台中,我收到有关力矩js的警告消息。
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
Run Code Online (Sandbox Code Playgroud)
我认为是因为这行代码;
function newDate(days) {
return moment().add(days, 'd').format('MM/DD');
}
Run Code Online (Sandbox Code Playgroud)
谢谢,请给我一个解决方案。
因此,chartjs正在动态创建x轴标签,并决定它每天可以显示两个标签,格式化后最终会显示两个相同的日期。
将新字段传递unit给该time对象并将其设置为day。这将导致图表在时间范围内每天仅显示一个刻度。(例如小提琴)
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'day',
}
}],
},
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |