我最近参与了chart.js
的时间尺度表。但现在我想在data
标签,如01-02-2017,02-06-2017而不是“2017年2月4日”,“2017年2月9日”等等。
这里是我的代码
var aR = null; //store already returned tick
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
/* labels: ["01-01-2017", "03-01-2017", "04-02-2017", "09-02-2017", "03-03-2017", "17-03-2017","23-03-2017","09-04-2017"],*/
labels: ["1 January 2017", "3 January 2017","12 January 2017","20 January 2017","22 January 2017","23 January 2017","27 January 2017", "4 February 2017", "9 February 2017", "3 March 2017", "17 March 2017","23 March 2017","15 March 2017"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgb(255, 99, 132)',
data: [12, 16, 2, 7, 15, 5, 11, 10, 11, 1, 8, 9, 15],
lineTension: 0
}]
},
options: {
scales: {
xAxes: [{
ticks: {
autoSkip: false,
callback: function(e) {
var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
if (tick != aR) {
aR = tick;
return tick;
}
}
}
}],
yAxes: [{
ticks: {
min: 0,
max: 30
}
}]
}
}
});
那我怎么能重新标记他们的标签。请指导我。谢谢..
答案 0 :(得分:0)
我假设您希望将x轴标签显示为01 January 2017
而不是01-01-2017
。
如果是这样的话,你需要重新格式化你的日期字符串,你可以用以下方式完成...
var date_arr = ["01-01-2017", "03-01-2017", "04-02-2017", "09-02-2017", "03-03-2017", "17-03-2017", "23-03-2017", "09-04-2017"];
var labels = formatDate(date_arr);
function formatDate(arr) {
var new_date = [];
arr.forEach(function(d) {
var date = d.split('-')[0].replace(/\d+/, function(e) {
switch (e) {
case '01': case '21': case '31':
return e + 'st';
case '02': case '22':
return e + 'nd';
case '03': case '23':
return e + 'rd';
default:
return e + 'th';
}
});
var month = new Date(d.split('-')[1]).toLocaleString('en-us', {
month: "long"
});
var year = d.split('-')[2];
new_date.push(date + ' ' + month + ' ' + year);
});
return new_date;
}
/*** GENERATE CHART ****/
var aR = null; //store already returned tick
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: "My First dataset",
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgb(255, 99, 132)',
data: [12, 16, 10, 11, 9, 15, 13, 16],
lineTension: 0
}]
},
options: {
scales: {
xAxes: [{
ticks: {
autoSkip: false,
callback: function(e) {
var tick = e.match(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Oct|Nov|Dec).*?\d+/g)[0];
if (tick != aR) {
aR = tick;
return tick;
}
}
}
}],
yAxes: [{
ticks: {
min: 0,
max: 30
}
}]
}
}
});

<canvas id="myChart" height="200"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
&#13;