我使用线图.js,我想显示我的线图有两条线(实际上是动态数据集),底部有位置和标签,底部有月份,现在我的图表只显示最后一组数据。
我的数据是这样的
{
location: "Apartment A",
color: "#b168ac",
set_data: [{
month: 1,
value: 3500
},{
month: 2,
value: 2700
},{
month: 3,
value: 1500
}]
},
{
location: "Apartment B",
color: "#b168aa",
set_data: [{
month: 1,
value: 1700
},{
month: 2,
value: 2800
},{
month: 3,
value: 3200
}]
}
我的代码是这样的。
var obj = JSON.parse(data);
$.each(obj,function(i,item){
var locate = [];
var amt = [];
var color = [];
var item_set = [];
locate.push(item.location);
var m = [];
var val = [];
var item_s = item.set_data;
$.each(item_s,function(i2,item2){
val.push(item2.value);
m.push(item2.month);
var chartdata = {
labels: m,
datasets : [{
label:locate,
data: val,
backgroundColor: item.color,
borderWidth: 1,
fill: false,
}]
};
var ctx = document.getElementById("graph_by_usage").getContext('2d');
var LineChart = new Chart(ctx,{
type : 'line',
data : chartdata,
options: {
responsive:true
}
});
});
});
数据应该是这样的 https:/codepen.iok3nopenpbYGVa 请给我建议。谢谢你。
假设你的数据是一个JSON数组,你可以生成标签和数据集如下。
const labels = baseData[0].set_data.map(v => v.month);
const dataSets = [];
baseData.forEach(o => dataSets.push({
label: o.location,
data: o.set_data.map(v => v.value),
borderColor: o.color,
borderWidth: 1,
fill: false
})
);
请看下面的可运行代码示例。
const baseData = [{
location: "Apartment A",
color: "red",
set_data: [
{ month: 1, value: 3500 },
{ month: 2, value: 2700 },
{ month: 3, value: 1500 }
]
},
{
location: "Apartment B",
color: "blue",
set_data: [
{ month: 1, value: 1700 },
{ month: 2, value: 2800 },
{ month: 3, value: 3200 }
]
}
];
const labels = baseData[0].set_data.map(v => v.month);
const dataSets = [];
baseData.forEach(o => dataSets.push({
label: o.location,
data: o.set_data.map(v => v.value),
borderColor: o.color,
borderWidth: 1,
fill: false
})
);
new Chart('graph_by_usage', {
type : 'line',
data: {
labels: labels,
datasets: dataSets
},
options: {
responsive:true
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="graph_by_usage" height="90"></canvas>