Using Different Colors In a Chart - javascript

My Code:
<div><canvas id="canvas_line" height="200" width="800"></canvas></div>
<div><canvas id="canvas_bar" height="200" width="800"></canvas></div>
<script>
var lineChartData = {
labels : ["14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
label: "CPU IDLE",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var barChartData = {
labels : ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [85,35,65,59,90,81,56,55,40,100]
}
]
}
var ctx_line = document.getElementById("canvas_line").getContext("2d");
window.myLine = new Chart(ctx_line).Line(lineChartData, {
responsive: true
});
var ctx_bar = document.getElementById("canvas_bar").getContext("2d");
window.myLine = new Chart(ctx_bar).Bar(barCharData, {
responsive: true
});
</script>
It looks like this, everything is grey.
But I'd like to change the lineChart's pointColor and barChart's fillcolor to red if its data is above 80, the data below 80 are still grey.
I want it like this, but I don't know how to use different colors in a canvas.
<!DOCTYPE html>
<html>
<head>
<title>123</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/Chart.js/0.2.0/Chart.min.js"></script>
</head>
<body>
<canvas id="chartCanvas" height="200" width="800"></canvas>
<script>
$(document).ready(function() {
var chartData = {
labels: ["12:00","13:00","14:00","15:00","16:00","17:00","18:00","19:00","20:00","22:00"],
datasets: [
{
data : [85,35,65,59,90,81,56,55,40,100],
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)'
}
]
}
var chartCanvas = document.getElementById("chartCanvas").getContext("2d");
var barChart = new Chart(chartCanvas).Bar(chartData, {responsive: true});
// Set warning color
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length ; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
});
</script>
</body>
</html>

You have to loop to all the bars/points of your chart, check if the value is over 80 and set the color.
Here is an example for the bar chart:
var bars = barChart.datasets[0].bars;
for(var i = 0; i < bars.length; i++) {
if(bars[i].value > 80) {
bars[i].fillColor = "rgba(255, 0, 0, 0.2)";
bars[i].strokeColor = "rgba(220, 0, 0, 0.5)";
}
}
// Update the chart
barChart.update();
Check out this fiddle for a working demo.
To set the color on a line chart you just have to iterate over the points instead of the bars:
var points = lineChart.datasets[0].points;
And of course set the pointColor or whatever you want.

Related

Fill in JSchart with JSON file

I'm creating a JSchart with some JSON data i gathered from a FitBit.
https://jsfiddle.net/d0708akg/4/
This is my Code:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js"></script>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div class="chart-wrap" style="width: 100%; height: 100%;">
<canvas id="canvas" style="width: 100%; height: auto;"></canvas>
</div>
<div id="js-legend" class="chart-legend"></div>
</body>
</html>
<script>
$.getJSON("fitbitdata.json", function (json) {
// will generate array with ['Monday', 'Tuesday', 'Wednesday']
var labels = json.map(function(item) {
return item.Weight;
});
});
//there was a comma separating these two var declarations. Changed it to a `;`
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "Gewicht",
fillColor : "rgba(141,255,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
backgroundColor : "rgba(215, 44, 44, 0.2)",
pointStrokeColor : "#fff",
data: []
},
{
label : "BMI",
fillColor : "rgba(215, 40, 40, 0.9)",
strokeColor : "rgba(151,187,205,1)",
backgroundColor : "green",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : []
}
]
};
// I put the canvas element in a var just to clean up the 'new Chart' syntax
var canvas = document.getElementById("canvas").getContext("2d");
//this is the new syntax
var myLine = new Chart(canvas, {
type: 'line',
data: lineChartData//,
//options: options //if you had any to pass
});
</script>
What I'm trying to do is this:
I've got a json file with some data like this:
[{<br>
"Datum":"Week 1",
"Weight":74,
"BMI":21.39,
"Fat":0,
"CaloriesBurned":2.103,
"Steps":3.53,
<br>
}]
when I do alert(labels)
It shows all the values. Why not in my jschart?

Put chart.js chart inside JQuery tooltip?

I would like to display chart.js's bar chart inside a tooltip.
Is this possible?
$(function() {
$( document ).tooltip({
track: true,
content:function () {var temp = $(this).prop('title');
temp = theBigArray[temp] //THIS IS THE JSON DATA CONTAINER FOR EACH SENTENCE
var barChartData = {
labels : ["Future","Present","Past"],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,0.8)",
highlightFill : "rgba(151,187,205,0.75)",
highlightStroke : "rgba(151,187,205,1)",
data : [temp[2], temp[3], temp[4]]
}
]
}
var ctx = document.getElementById("canvas").getContext("2d");
var myTable = new Chart(ctx).Bar(barChartData, {
responsive : false
});
return '<canvas id="canvas"></canvas>';
}
});
When "canvas" is under , and displayed on html, it works fine. But, it fails to show inside the tooltip javascript when I return the content of the tooltip with div.
You need to create the canvas element before you call getElementById on it. Also, the canvas element needs to be sized for Chart.js to work properly.
Use this
$(function() {
$( document ).tooltip({
track: true,
open: function (event, ui) {
$('.ui-tooltip-content > div').append($("#canvas"))
},
content: function () {
var temp = $(this).prop('title');
var temp = theBigArray[temp] //THIS IS THE JSON DATA CONTAINER FOR EACH SENTENCE
var barChartData = {
labels: ["Future", "Present", "Past"],
datasets: [
{
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: [temp[2], temp[3], temp[4]]
}
]
}
$('body').append($("<canvas id='canvas' width='200' height='100'></canvas>"))
var ctx = document.getElementById("canvas").getContext("2d");
var myTable = new Chart(ctx).Bar(barChartData, {
responsive: false,
animation: false
});
return '<div></div>';
}
})
});
with CSS
<style>
body > #canvas {
position: fixed;
visibility: hidden;
}
</style>

Updating chart.js in AJAX doesn't render the graph properly

I am trying to plot a line chart using chart.js with AJAX but the chart is not plotted properly when data comes from server. The chart is plotting fine on window onload event but with AJAX it failed to render properly. What could be the issue? Here is my code -
index.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>AJAX JSON Chart</title>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript">
var randomScalingFactor = function(){ return Math.round(Math.random()*100)};
var lineChartData = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
label: "My First dataset",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,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: false
});
}
// ajax part of chart //
$(document).ready(function(e) {
$("#frm1").submit(function(){
var canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
var btnchart = $("#btnchart").attr("name") + "=" + $("#btnchart").val();
$.ajax({
//beforeSend: function(){ sendRequest("canvas"); },
cache: false,
type: "POST",
dataType: "json",
url: "ajax/chart.php",
data: $(this).serialize() + "&" + btnchart,
success: function(data){
//alert(data.labels);
//alert(data.points);
renderGraph(data.labels, data.points, ctx);
},
});
return false;
});
});
var renderGraph = function (labels, points, ctx) {
var lineChartData = {
labels: "[" + labels + "]",
datasets: [
{
label: "Recent Orders",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: "[" + points + "]",
}
]
};
var myChart = new Chart(ctx)
.Line(lineChartData, {
responsive: false,
animation: false
});
myChart.update(lineChartData);
}
function sendRequest(id)
{
$("#"+id).html('<div style="width:100px; margin:0 auto;"><img id="loader-img" alt="" src="images/preloader.gif" width="100" height="100" /></div>');
}
</script>
</head>
<body>
<div style="width:30%">
<div>
<canvas id="canvas" height="450" width="960"></canvas>
</div>
</div>
<form id="frm1" name="frm1" method="post" action="">
<input type="submit" name="btnchart" id="btnchart" value="Draw Chart" />
</form>
</body>
</html>
chart.php:
<?php
$labels = array('29 April 2015', '30 April 2015', '1 May 2015', '2 May 2015', '3 May 2015', '4 May 2015', '5 May 2015');
$points = array('100', '250', '10', '35', '73', '0', '25');
echo json_encode(array('labels' => $labels, 'points' => $points));
?>
On first time page loads, the output is:
After clicking button "Draw Chart", the output comes through AJAX is:
But when i hover my mouse over the image, it automatically converts into first image i.e. the first correct graph when window was loaded. Strange!!!
so before drawing your chart again, what you can do just destroy the earlier created chart with
myChart.destroy();
or
myChart.clear();
and then redraw your chart. Then hopefully it will work correct

Chart.js - Multiple Line Charts - Only Show Last Chart

I am using chart.js to show multiple line charts on one page. However, only the last chart shows even though I have called them #canvas1 and #canvas2. Something must be conflicting somewhere and I've tried most things but not having any joy. Here are two charts, it only shows the last one:
Graph One
<script type="text/javascript">
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
label: "Target",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [160000,175000,185000,180000,185000,185000,185000,195000,200000,0,0]
},
{
label: "Sales",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [<?php echo $stockJanuary ?>,<?php echo $stockFebruary ?>,<?php echo $stockMarch ?>,<?php echo $stockApril ?>,<?php echo $stockMay ?>,<?php echo $stockJune ?>,<?php echo $stockJuly ?>,<?php echo $stockAugust ?>,<?php echo $stockSeptember ?>,<?php echo $stockOctober ?>,<?php echo $stockNovember ?>,<?php echo $stockDecember ?>]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas1").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
Graph Two:
<script type="text/javascript">
var lineChartData = {
labels : ["January","February","March","April","May","June","July","August","September","October","November","December"],
datasets : [
{
label: "Target",
fillColor : "rgba(220,220,220,0.2)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(220,220,220,1)",
data : [19000,21000,23000,25000,27000,29000,31000,32000,33000,0,0]
},
{
label: "Sales",
fillColor : "rgba(151,187,205,0.2)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
pointHighlightFill : "#fff",
pointHighlightStroke : "rgba(151,187,205,1)",
data : [<?php echo $northJanuary ?>,<?php echo $northFebruary ?>,<?php echo $northMarch ?>,<?php echo $northApril ?>,<?php echo $northMay ?>,<?php echo $northJune ?>,<?php echo $northJuly ?>,<?php echo $northAugust ?>,<?php echo $northSeptember ?>,<?php echo $northOctober ?>,<?php echo $northNovember ?>,<?php echo $northDecember ?>]
}
]
}
window.onload = function(){
var ctx = document.getElementById("canvas2").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
}
</script>
Your help would be much appreciated, been bugging me for a while now!
Thanks in advance
Try using different names for the two ctx variables.
window.onload = function(){
var ctx = document.getElementById("canvas2").getContext("2d");
window.myLine = new Chart(ctx).Line(lineChartData, {
responsive: true
});
var ctx2 = document.getElementById("canvas1").getContext("2d");
window.myLine = new Chart(ctx2).Line(lineChartData2, {
responsive: true
});
}
Initially I had the exact same problem as the original question and Tried Arpan Das suggestion, but did not get right on the first try.
Anyone else having the same problem, might find it useful to have a look at this working example of multiple graphs on one page:
<div id="canvas-holder">
<canvas id="A" width="300" height="300"/><br>
</div>
<div id="canvas-holder">
<canvas id="B" width="300" height="300"/><br>
</div>
<script>
var pieDataA = [ { value: 50, color: "#F6BFBD" } ];
var pieDataB = [ { value: 50, color: "#00BFBD" } ];
window.onload = function(){
var ctx1 = document.getElementById("A").getContext("2d");
window.myPieA = new Chart(ctx1).Pie(pieDataA);
var ctx2 = document.getElementById("B").getContext("2d");
window.myPieB = new Chart(ctx2).Pie(pieDataB); };
</script>
Fiddle link: http://fiddle.jshell.net/2omjx9dn/
The mistake in the initial code is that you call the function window.onload multiple times.
Unfortunately, it's not that simple. The first onload event handler will be replaced when the second onload event handler is executed. [and so one untill last onload.window]
That problem usually appears when you want to create the graphs separately and, for example, include with php in your page graphs (because in each php page you are calling window.onload)
Easy solution:
function start() {
func1();
func2();
}
window.onload = start;
Simon Willison proposed:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
/* more code to run on page load */
});
Multiple Line charts using chart.js
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CampComparison.aspx/getLineChartDataload",
data:{},
async: true,
cache: false,
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
})
function OnSuccess_(reponse) {
var aData = reponse.d;
var aLabels = aData[0];
var aDatasets1 = aData[1];
var aDatasets2 = aData[2];
var aDatasets3 = aData[3];
var aDatasets4 = aData[4];
var aDatasets5 = aData[5];
var lineChartData = {
labels: aLabels,
datasets: [
{
label: "Data1",
//fill:false,
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(200,122,20,1)",
data: aDatasets1
},
{
label: "Data2",
fillColor: 'rgba(0,0,0,0)',
strokeColor: 'rgba(220,180,0,1)',
pointColor: 'rgba(220,180,0,1)',
data: aDatasets2
},
{
label: "Data5",
fillColor: "rgba(0,0,0,0)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(152,188,204,1)",
data: aDatasets3
},
{
label: "Data4",
fillColor: 'rgba(0,0,0,0)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
data: aDatasets4
},
{
label: "Data4",
fillColor: 'rgba(0,0,0,0)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
data: aDatasets5
},
]
}
Chart.defaults.global.animationSteps = 50;
Chart.defaults.global.tooltipYPadding = 16;
Chart.defaults.global.tooltipCornerRadius = 0;
Chart.defaults.global.tooltipTitleFontStyle = "normal";
Chart.defaults.global.tooltipFillColor = "rgba(0,160,0,0.8)";
Chart.defaults.global.animationEasing = "easeOutBounce";
Chart.defaults.global.responsive = true;
Chart.defaults.global.scaleLineColor = "black";
Chart.defaults.global.scaleFontSize = 16;
//lineChart.destroy();
//document.getElementById("canvas").innerHTML = ' ';
//document.getElementById("chartContainer").innerHTML = ' ';
//document.getElementById("chartContainer").innerHTML = '<canvas id="canvas" style="width: 650px; height: 350px;"></canvas>';
//var ctx = document.getElementById("canvas").getContext("2d");
//ctx.innerHTML = "";
//var pieChartContent = document.getElementById('pieChartContent');
//pieChartContent.innerHTML = ' ';
//$('#pieChartContent').append('<canvas id="canvas" width="650px" height="350px"><canvas>');
//ctx = $("#canvas").get(0).getContext("2d");
var ctx = document.getElementById("canvas").getContext("2d");
var lineChart = new Chart(ctx).Line(lineChartData, {
bezierCurve: true,
chartArea: { width: '62%' },
responsive: true,
pointDotRadius: 10,
scaleShowVerticalLines: false,
scaleGridLineColor: 'black'
});
}
function OnErrorCall_(repo) {
//alert(repo);
}
});
//});
</script>
C#code
--------
[WebMethod(EnableSession = true)]
public static List<object> getLineChartDataload()
{
List<object> iData = new List<object>();
List<string> labels = new List<string>();
string advertiserid = HttpContext.Current.Session["AccountID"].ToString();
if (!string.IsNullOrEmpty(advertiserid))
{
// string StartDate = DateTime.Now.AddDays(-180).ToString("yyyy-MM-dd");
string StartDate = DateTime.Now.AddDays(-60).ToString("yyyy-MM-dd");
string EndDate = DateTime.Now.ToString("yyyy-MM-dd");
string strcampaignid = string.Empty;
DataTable dt = new DataTable();
int i = 0;
chatBL objcampid = new chatBL();
string query = "select distinct top 3 Campaignid,CampaignName from campaign where advertiserid='" + advertiserid + "' order by CampaignName";
dt = objcampid.commonFuntionGetData2(query);
foreach (DataRow drow in dt.Rows)
{
strcampaignid += drow["Campaignid"].ToString() + ",";
}
if (!string.IsNullOrEmpty(strcampaignid))
{
strcampaignid = strcampaignid.Substring(0, strcampaignid.Length - 1);
}
string[] campaignid = strcampaignid.Split(',');
//First get distinct Month Name for select Year.
// string query1 = "select top 10 cast(createddatetime as date) as month_name from advertiser where CurrentBal>0 order by CurrentBal";
//query1 += " ";
// query1 += " order by month_number;";
foreach (string strcamp in campaignid)
{
if (i == 0)
{
chatBL objblabel = new chatBL();
// DataTable dtLabels = objblabel.Topupmonthly("5E8EF1E9-67BF-489C-84CB-AFF0BB0FE707", "2015-09-18", "2016-02-25", "months");
DataTable dtLabels = objblabel.Topupmonthly2(strcamp, StartDate, EndDate, "months");
foreach (DataRow drow in dtLabels.Rows)
{
labels.Add(drow["InsDateTime"].ToString().Substring(2, 7));
}
iData.Add(labels);
}
// string query_DataSet_1 = "select top 10 CurrentBal from advertiser where CurrentBal>0 order by CurrentBal";
//query_DataSet_1 += " (orders_quantity) as total_quantity from mobile_sales ";
//query_DataSet_1 += " where YEAR(orders_date)='" + year + "' and mobile_id='" + mobileId_one + "' ";
//query_DataSet_1 += " group by month(orders_date) ";
//query_DataSet_1 += " order by month_number ";
chatBL objbl = new chatBL();
DataTable dtDataItemsSets_1 = objbl.Topupmonthly2(strcamp, StartDate, EndDate, "months");
List<double> lst_dataItem_1 = new List<double>();
foreach (DataRow dr in dtDataItemsSets_1.Rows)
{
lst_dataItem_1.Add(Convert.ToDouble(dr["CPACOUNT"].ToString()));
}
iData.Add(lst_dataItem_1);
//string query_DataSet_2 = "select top 10 Totalspent from advertiser where CurrentBal>0 order by CurrentBal";
//query_DataSet_2 += " (orders_quantity) as total_quantity from mobile_sales ";
//query_DataSet_2 += " where YEAR(orders_date)='" + year + "' and mobile_id='" + mobileId_two + "' ";
//query_DataSet_2 += " group by month(orders_date) ";
//query_DataSet_2 += " order by month_number ";
//chatBL objbl1 = new chatBL();
//DataTable dtDataItemsSets_2 = objbl1.Topupmonthly("5E8EF1E9-67BF-489C-84CB-AFF0BB0FE707", "2015-09-18", "2016-02-25", "months");
//List<double> lst_dataItem_2 = new List<double>();
//foreach (DataRow dr in dtDataItemsSets_2.Rows)
//{
// lst_dataItem_2.Add(Convert.ToDouble(dr["CPACOUNT"].ToString()));
//}
//iData.Add(lst_dataItem_2);
i = i + 1;
}
}
return iData;
}
I was having the same issue and although it was a minor lack of attention from my part, it took me a while to figure it out: I was using the same data reference for all charts with small changes.
Here is the problem and solution:
chartData = {
labels: Array(dataLeft.length).fill(""), // No labels on X axis
datasets: [
{
label : "Lado Esquerdo",
backgroundColor : "rgba(50,192,50,0.4)",
borderColor : "rgba(75,192,75,1)",
pointBorderColor : "rgba(75,192,75,1)",
data : dataLeft,
},
{
label : "Lado Direito",
backgroundColor : "rgba(192,50,50,0.4)",
borderColor : "rgba(192,75,75,1)",
pointBorderColor : "rgba(192,75,75,1)",
data : dataRight,
}
]
};
I was using this chartData for all charts, but before constructing a new chart, I was changing the data attribute (chartData.datasets[0].data = some_specific_value_for_each_chart)
But since this is a reference, I was changing the data of all the previously constructed charts, setting their data to the same data of the last chart initialized!
I don't know if I took the best approach, but to solve this I returned the data dynamically when initializing the charts
createChartData = function(dataRight, dataLeft) {
return {
labels: Array(dataLeft.length).fill(""), // No labels on X axis
datasets: [
{
label : "Lado Esquerdo",
backgroundColor : "rgba(50,192,50,0.4)",
borderColor : "rgba(75,192,75,1)",
pointBorderColor : "rgba(75,192,75,1)",
data : dataLeft,
},
{
label : "Lado Direito",
backgroundColor : "rgba(192,50,50,0.4)",
borderColor : "rgba(192,75,75,1)",
pointBorderColor : "rgba(192,75,75,1)",
data : dataRight,
}
]
}
};
And then to init the chart:
var chart1 = new Chart(ctx1, {
type: 'line',
data: createChartData(graphData1, graphData2),
options: chartOptions
});

chart.js in meteor not drawing

In a meteor project, I have copied the demo code from chart.js into my client folder as follows:
function drawChart(){
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
new Chart(ctx).Line(data);
}
Meteor.startup(function() {
drawChart();
});
In the HTML I have:
<canvas id="myChart" width="400" height="400"></canvas>
Nothing is drawn, nor any errors thrown. The same code run in the console produces a chart. What am I missing?
I am using the meteor-chartjs library.
Add the canvas to a template
<template name="chart">
<canvas id="myChart" width="400" height="400"></canvas>
</template>
Use the template rendered callback to call your drawChart function
Template.chart.rendered = function(){
drawChart();
}
function drawChart(){
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
//Get context with jQuery - using jQuery's .get() method.
//var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
//var myNewChart = new Chart(ctx);
//new Chart(ctx).Line(data);
//modify this
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).PolarArea(data);
}
Meteor.startup(function() {
drawChart();
});

Categories

Resources