我使用Chart.js作为条形图。我需要在条形图中显示12个月的数据。所以在2016年我只有feb,mar和apr我有数据。在标签im加载所有12个月与年份示例2016年1月至2016年12月。
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var startmonth = ["Dec", "Nov", "Oct", "Sep", "Aug", "Jul",
"Jun", "May", "Apr", "Mar", "Feb", "Jan"
];
var itemMonths = [];
var start;
var end = 11;
var month;
var year;
var date = new Date();
month = date.getMonth();
year = parseInt(Result[0].yearfromdb); //getting createddate year from db
start = 0;
for (var i = 0; i < 12; i++) {
var months = monthNames[start];
itemMonths.push(months + year);
start = start + 1;
if (start == 12) {
start = 0;
year = year + 1;
}
}
for (var i in Result)
{
itemCountList.push( Result[i].Counts );// Result is List from Db contains Feb,mar and apr total counts..
}
var mybarChart = null;
var ctx = document.getElementById("mybarChart");
mybarChart = new Chart(ctx, {
type: 'bar',
data: {
labels: itemMonths
,
datasets: [{
label: 'Total Count',
backgroundColor: "#26B99A",
data: itemCountList
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
steps: 10,
stepValue: 5,
max: 100
}
}],
xAxes: [{
steps: 10,
stepValue: 5,
max: 12
}]
}
}
});
我的问题是,数据是从jan,feb,march而不是feb,mar,apr .... 这该怎么做?请帮帮我......
答案 0 :(得分:1)
var Result=[];
Result.push({Months:"Feb",Years:2016,Counts:6});
Result.push({Months:"Mar",Years:2016,Counts:1});
Result.push({Months:"Apr",Years:2016,Counts:1});
for(var j in itemMonths)
{
for(var i in Result)
{
if(itemMonths[j]==Result[i].Months+Result[i].Years)
{
itemCountList[j]=Result[i].Counts;
//itemCountList.push( Result[i].Counts )
}
}
}
试试这个......
答案 1 :(得分:0)
你的开始取决于年份,所以:
year = parseInt(Result[0].yearfromdb); //getting createddate year from db
start = (year === 2016? 1 : 0);
答案 2 :(得分:0)
您的代码存在的问题是数据点的数量不等于标签的数量。由于此图表正在绘制x轴标签开头右侧可用的3个数据点。
要解决此问题,您可以使您的数据点数与数据标签数相同。
试试这个,我在这里检查数据点是否在结果数组中的给定月份可用,然后在数据点数组中插入该值,否则插入0值。
for (var i = 0; i < 12; i++) {
var months = monthNames[start];
var monthValue = 0;
itemMonths.push(months + year);
start = start + 1;
if (start == 12) {
start = 0;
year = year + 1;
}
var dataObj = $.grep(Result, function(a) {
return a.Months == months
})[0];
var monthValue = dataObj !== undefined ? dataObj.Counts : 0;
itemCountList.push(monthValue)
}