The below JavaScript code displays line chart using chart.js. The code works fine however, if you look at the part of the code near labels I am trying to pass it dynamically using a variable instead of having a static list of months. For example I just want to pass from Jan - May.
I am using a variable x to do that but it would not work as a separate labels it would display as one label example in the image. Is there a way i can pass those label dynamically ? I don't want to use separate variables since my list will be based on n.
Original
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()]
}
Modified Version
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
});
}
What you want is to declare x
(currently declared as a string) as an array instead. The, you join the two arrays together using .concat
so that your labels
property has the full list:
var x = ["January", "February"];
var lineChartData = {
labels : x.concat(["March","April","May","June","July","August","September","October","November","December"]),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.