如何在图表中显示数据? [英] How to show data in a chart?
本文介绍了如何在图表中显示数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,实际上我正在从数据库中检索一些数据数据就是这种格式
Hey there actually I am retrieving some data from database The data is is like this format
id: "5"
p_amount: "120"
p_date: "09/20/2019"
p_id: "12345"
p_method: "Bank"
p_status: "OPEN"
这就是我在ajax响应中所做的事情,我将日期月份转换为其名称
This is what i did in ajax response, I convert the month of date in its name
success: function(response){
var obj=JSON.parse(response);
if(obj!=""){
$.each(obj, function(i, item) {
var selectedMonthName = months[obj[i].p_date.slice(0,2)-1];
});
}
现在我有另一个名为 main.js 的文件,并且我使用javascript作了一个图表
Now i have another file of name main.js and i made a chart in javascript
(function ($) {
// USE STRICT
"use strict";
try {
//WidgetChart 1
var ctx = document.getElementById("widgetChart1");
if (ctx) {
ctx.height = 115;
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July','August','September','October','November','December'],
type: 'line',
datasets: [{
data: [0, 0, 0, 0, 0, 0, 0,0,0,0,0,0], //Here data should be added e.g, if month is september the value p_amount should add here in 8th index
label: 'Dataset',
backgroundColor: 'rgba(255,255,255,.1)',
borderColor: 'rgba(255,255,255,.55)',
},]
},
options: {
maintainAspectRatio: true,
legend: {
display: false
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
responsive: true,
scales: {
xAxes: [{
gridLines: {
color: 'transparent',
zeroLineColor: 'transparent'
},
ticks: {
fontSize: 2,
fontColor: 'transparent'
}
}],
yAxes: [{
display: false,
ticks: {
display: false,
}
}]
},
title: {
display: false,
},
elements: {
line: {
borderWidth: 0
},
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 4
}
}
}
});
}
} catch (error) {
console.log(error);
}
})(jQuery);
现在我想要当我获得月份名称时,应该更新其他js文件中的数据(从数据库中检索到的数据)
Now i want when i get the month name the data(which is retrieved from DB) in other js file should be updated
推荐答案
我们使用了类似的方法,将chart.js对象设置为全局对象,从Ajax响应中设置其数据并调用了update方法.
We used something like this, made chart.js object global, set its data from Ajax response and called update method.
var labels = [];
var data = [];
var smallDB = {};
var lastYear = 0;
var limit = 5; // limit history to (5) years
var obj = TestData();
for (var i in obj) {
var d = new Date(obj[i].b_date);
var idy = d.getFullYear();
lastYear = Math.max(lastYear, idy)
var num = parseInt(obj[i].b_amount);
smallDB[idy] = (smallDB[idy] || 0) + num;
}
lastYear++;
for(var i=0;i<limit;i++) {
labels[i] = i+lastYear-limit;
data[i] = smallDB[i+lastYear-limit] || 0;
console.log(labels[i], data[i]);
}
function TestData() {
return [{
b_date:"11/01/2017",
b_amount:"110"
},{
b_date:"10/01/2016",
b_amount:"100"
},{
b_date:"01/01/2020",
b_amount:"200"
},{
b_date:"12/01/2018",
b_amount:"120"
}];
};
此限制持续5年.
这篇关于如何在图表中显示数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文