我用下面的代码创建了这个图表,数据比较需要多年的时间跨度。我有一个类似于下面的数据集,但每组可以比另一个短或长。
{ label: 2013, data: [{y: 266, x: 02/29/2013},{ y: 311, x: 04/01/2013}]},
{ label: 2014, data: [{y: 403, x: 01/09/2014},{ y: 705, x: 08/01/2014},{ y: 885, x: 12/05/2014}]},
{ label: 2014, data: [{y: 550, x: 04/12/2015}]}
我希望它像这样绘制,从 1 月到 12 月,但可以读取介于两者之间的每一天(数据点)的工具提示:
关于数据是否应该采用不同的格式或可以使用的图表属性有什么建议吗?
//loop through each year to build our objects needed for the chart
$.each(jsonData.results, function(i, row) {
data = row.dt;
CumulativeDayTotal = 0
yAxis = [];
$.each(data, function(i, row) {
CumulativeDayTotal = parseInt(row[yValueKey]) + parseInt(CumulativeDayTotal);
formattedDate = new Date(row["DATE_F"]);
formattedDate = (formattedDate.getMonth() + 1) + '/' + formattedDate.getDate() + '/' + formattedDate.getFullYear();
yAxis.push("{ y: " + CumulativeDayTotal + ", x: '" + formattedDate + "'}");
});
//create color for each new line/year
lineColor = dynamicColors();
chartPlaceHolders += '{label:"' + row.year + '", data:[' + yAxis + '],' +
'fill: false,' +
'lineTension: 0.1,' +
'backgroundColor: "' + lineColor + '",' +
'borderColor: "' + lineColor + '",' +
'borderCapStyle: "butt",' +
'borderDash: [],' +
'borderDashOffset: 0.0,' +
'borderJoinStyle: "miter",' +
'pointBorderColor: "rgba(75,192,192,1)",' +
'pointBackgroundColor: "#fff",' +
'pointBorderWidth: .2,' +
'pointHoverRadius: 5,' +
'pointHoverBackgroundColor: "rgba(75,192,192,1)",' +
'pointHoverBorderColor: "rgba(220,220,220,1)",' +
'pointHoverBorderWidth: 0,' +
'pointRadius: .5,' +
'pointHitRadius: 1' +
'},';
});
}
//remove last comma from string
chartPlaceHolders = chartPlaceHolders.replace(/,\s*$/, "");
chartPlaceHolders = "[" + chartPlaceHolders + "]";
var initFields = eval("(" + chartPlaceHolders + ")");
//call newly created elements into a variable to pass along to the other functions
var ctx = $("#primaryChart")[0].getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: initFields
},
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: yAxisLabel
}
}],
xAxes: [{
type: 'time',
time: {
unit: 'month',
displayFormats: {
max: 'December',
min: 'January',
//max: moment().startOf('year'),
//min: moment().endOf('year'),
'millisecond': 'MMMM',
'second': 'MMMM',
'minute': 'MMMM',
'hour': 'MMMM',
'day': 'MMMM',
'week': 'MMMM',
'month': 'MMMM',
'quarter': 'MMMM',
'year': 'MMMM',
}
},
scaleLabel: {
display: true,
labelString: xAxisLabel
}
}]
}
}
});