以下JavaScript代码使用chart.js显示折线图。代码工作正常但是,如果你看看标签附近的代码部分,我试图使用变量动态传递它,而不是有一个静态的月份列表。例如,我只想从1月到5月通过。
我使用变量x来执行此操作,但它不能作为单独的标签工作,它将在图像中显示为一个标签示例。有没有办法可以动态传递这些标签?我不想使用单独的变量,因为我的列表将基于n。
原创
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(54,61,251,0.2)",
strokeColor : "rgba(54,61,251,1)",
pointColor : "rgba(54,61,251,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(54,61,251,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
修改版
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var x = ' \"January\" , \"February\" ';
var lineChartData = {
labels : [x,"March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(54,61,251,0.2)",
strokeColor : "rgba(54,61,251,1)",
pointColor : "rgba(54,61,251,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(54,61,251,1)",
data : [randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor(),randomScalingFactor()]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
答案 0 :(得分:0)
您想要的是将x
(当前声明为字符串)声明为数组。您使用.concat
将两个数组连接在一起,以便您的labels
属性具有完整列表:
var x = ["January", "February"];
var lineChartData = {
labels : x.concat(["March","April","May","June","July","August","September","October","November","December"]),