我想创建一个包含多条线的图形,问题是代码会覆盖它创建的上一个线图,我将 x 和 y 轴值作为函数调用传递给代码,逻辑上它应该设置x 轴仅一次并将数据添加到 y(数据集中的数据)轴,以便在图表中拥有多条线
折线图中有多条线的静态代码
var config =
{
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"], //dates populated
datasets: [{
label: "My First dataset", //Name of reporting employee
backgroundColor: window.chartColors.red,
borderColor: window.chartColors.red,
data: [
randomScalingFactor(), //Add Datapoints(overall rating)
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
fill: false,
--------
}, {
label: "My Second dataset",
fill: false,
backgroundColor: window.chartColors.blue,
borderColor: window.chartColors.blue,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
],
}]
},
下面是我的代码,它尝试对动态传递的数据执行上述工作,动态性质导致了我之前提到的问题,
var config =
{
type: 'line',
data: {
labels:col_dates, //dates populated
datasets: [{
label:Name, //Name of reporting employee
backgroundColor:'#00FFFF',
borderColor: '#00FFFF',
data:O_ratings,
fill: false,
}]
},
options: {
responsive: true,
//animation: false,
title:{
display:true,
text:'Ratings Chart'
},
tooltips: {
mode: 'index', //Populate the entire datalist here
intersect: false,
},
hover: {
mode: 'nearest',
intersect: false
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Dates'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
我使用了两个数组 col_dates(设置为 X 轴)和 O- ratings(设置为 Y 轴)
最佳答案
所以我没有足够的声誉点来实际评论这个问题。尝试删除背景颜色属性。第一个数据集的数据可能大于第二个数据集的数据。 我最近使用 php 完成了一个动态多线图表。我的图表配置如下:
var lineChartData = { //chart config options
labels : [<?php echo '"'.$labelArray.'"'; ?>],
datasets : [<?php echo $dataString; ?>],
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, {
type:"line",
fill: false,
data:lineChartData,
options: {
scales: {
xAxes: [{
ticks: {
autoSkip : true,
min: 2,
maxTicksLimit: 10
}
}]
},
},
responsive:true
});
$dataString
是我传递从外部 url 检索的所有数据的变量
$dataString = $dataString."{label : '$name','fill' : 'false', data : [$br_values], borderColor : '$color', backgroundColor : 'transparent' },";
如果我错过了什么,请告诉我,抱歉我没有早点回答这个问题,我两天前解决了这个问题。有关 Chart.js 的更多文档,请访问 here
点赞
关于javascript - 如何在chart.js中创建动态多线图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42295972/