Why this Javascript Chart won't work twice? - javascript

I've got some charts of http://canvasjs.com/javascript-charts/ and they are just wonderful! I used one of them and it worked perfectly :
<script type="text/javascript">
google.charts.load("current", {packages: ["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['ip', 'quantity'],
#foreach($ipsWithBytesDates as $item)
['{{$item['ip']}}', {{$item['counts']}}],
#endforeach
]);
var options = {
title: 'My Daily Activities',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
<div id="piechart_3d" style="width: 700px; height: 350px;"></div>
Now i need a second chart - I've already got it from the website and copy & paste it in my code.. but this haven't worked like I want.. the second chart works but overwrites the whole first chart.
The first chart is a column chart and is at the top of my page.. the second chart should be at the bottom.. but it isn't, it every time just overwrites my first chart -- could anybody tell me why? I think it's because of the "window.onload" at the beginning of both chart.. but I haven't really worked with javascript.
second chart:
<script type="text/javascript">
window.onload = function () {
var secchart = new CanvasJS.Chart("chartContainer2",
{
title:{
text: "U.S Smartphone OS Market Share, Q3 2012",
fontFamily: "Impact",
fontWeight: "normal"
},
legend:{
verticalAlign: "bottom",
horizontalAlign: "center"
},
data: [
{
//startAngle: 45,
indexLabelFontSize: 20,
indexLabelFontFamily: "Garamond",
indexLabelFontColor: "darkgrey",
indexLabelLineColor: "darkgrey",
indexLabelPlacement: "outside",
type: "doughnut",
showInLegend: true,
dataPoints: [
{ y: 53.37, legendText:"Android 53%", indexLabel: "Android 53%" },
{ y: 35.0, legendText:"iOS 35%", indexLabel: "Apple iOS 35%" },
{ y: 7, legendText:"Blackberry 7%", indexLabel: "Blackberry 7%" },
{ y: 2, legendText:"Windows 2%", indexLabel: "Windows Phone 2%" },
{ y: 5, legendText:"Others 5%", indexLabel: "Others 5%" }
]
}
]
});
secchart.render();
}
</script>
<script type="text/javascript"></script>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
source code from the chartlibary:

You need to have separate containers for each chart. Each snippet you've pasted is using var chart = new CanvasJS.Chart("chartContainer",
Try setting the 2nd chart to use a different element on your page.
<div id="chartContainer1" style="height: 300px; width: 100%;"></div>
<div id="chartContainer2" style="height: 300px; width: 100%;"></div>
var chart = new CanvasJS.Chart("chartContainer1", ...
var chart = new CanvasJS.Chart("chartContainer2", ...

Looks like both of these charts are being rendered in an element called "chartContainer". In both code snippets there is a div at the bottom with this name. You should change the name of this div for at least one of the charts.

Related

Getting Data points for canvasjs from a text file

Im trying to make a chart that dynamically gets plot values from a .txt file.
Here i can produce a simple chart with canvasjs this is the exact kind of chart i need to make except for it should get x values from a .txt file dynamically.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Percents",
fontFamily: "Impact",
fontWeight: "normal"
},
legend:{
verticalAlign: "bottom",
horizontalAlign: "center"
},
data: [
{
//startAngle: 45,
indexLabelFontSize: 20,
indexLabelFontFamily: "Garamond",
indexLabelFontColor: "darkgrey",
indexLabelLineColor: "darkgrey",
indexLabelPlacement: "outside",
type: "doughnut",
showInLegend: true,
dataPoints: [
{ y: 55, legendText:"55%", indexLabel: "55%" },
{ y: 45, legendText:"45%", indexLabel: "45%" },
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
Here i try but it fails
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="jquery.canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataPoints = [];
//Replace text file's path according to your requirement.
$.get("MYFILE.txt", function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({x: x , y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
});
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
It doesnt even give me any errors to debug.
EDIT: Content of .TXT file is very simple
MYFILE.txt
56
As this code, where I only replaced the ajax request by hardcoded data, is working, it has to be a problem with the ajax request itself.
var dataPoints = [];
(function(data) {
var x = 0;
var allLines = data.split('\n');
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
dataPoints.push({x: x , y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
})("1\n2\n4\n3");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
As we found out in the comments, it is as I assumed, that you are trying to run the files from the file system via file:/// in your browser, instead of a (local) web server, but ajax requests are not executable in this environment for security reasons.

Chart.js is not displaying in Visual Studio. it is not executing

Chart.js is not displaying in visual studio. it is not running don't know why.
I have checked with sublime, notepad, there it is working properly. but in Visual Studio asp.net platform it is not working.
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",//theme1
title:{
text: "Basic Column Chart - CanvasJS"
},
animationEnabled: false, // change to true
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "apple", y: 10 },
{ label: "orange", y: 15 },
{ label: "banana", y: 25 },
{ label: "mango", y: 30 },
{ label: "grape", y: 28 }
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Please refer Tutorials on adding Charts into ASP.NET MVC Applications for integrating CanvasJS Charts in your ASP .Net Application.

Annotations with Material Column Chart?

I have data in the form of
[[X, Y, {role: "annotation"}], [1,2, "something"], ...,...]
that I pass to
var data = google.visualization.arrayToDataTable(dataPattern); and plot with
var material = new google.charts.Bar(document.getElementById('distribution-over-range'));
material.draw(data, google.charts.Bar.convertOptions(options));
The annotations fail to appear. Any idea why?
google.charts.Bar component does not support annotations role but you could utilize google.visualization.BarChart from corechart package for that purpose as demonstrated below:
//google.load("visualization", "1.1", {packages:["bar"]});
google.load("visualization", "1.1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage', { role: "style" }, { role: 'annotation' }],
["King's pawn (e4)", 44, "#b87333",'43%'],
["Queen's pawn (d4)", 31, "silver", '31%'],
["Knight to King 3 (Nf3)", 12, "gold", '12%'],
["Queen's bishop pawn (c4)", 10, "color: #e5e4e2", '10%'],
['Other', 3, "green", '3%']
]);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('top_x_div'));
var chart = new google.visualization.BarChart(document.getElementById("top_x_div"));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="top_x_div" style="width: 640px; height: 480px;"></div>

Change the color of some bars in google chart

I created an horizontal bar chart with Google Charts and I want to change the color of the bars that belongs to a certain range, I tried to do it by many ways
but in vain, here is my code :
google.load("visualization", "1.1", {packages:["bar"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.arrayToDataTable([
['Agents', 'Percentage' ],
<?php
for($i=0;$i<sizeof($name);$i++){
echo '[\''.$name[$i].'\','.$count[$i].'],';
}
?>
]);
var options = {
title: 'EKMS Usage per agent',
width: 900,
legend: { position: 'none' },
chart: { title: 'EKMS Usage per agent',
subtitle: 'By percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
chart.draw(data, options);
};
$name and $count are two arrays that I retrieved from my database and that has the same length, I tried to add a column { role: "style" } in the variable data and to
assign colors using a test like this :
var data = new google.visualization.arrayToDataTable([
['Agents', 'Percentage', { role: "style" } ],
<?php
for($i=0;$i<sizeof($name);$i++){
if($count[$i]<50)
echo '[\''.$name[$i].'\','.$count[$i].',\'red\'],';
else
echo '[\''.$name[$i].'\','.$count[$i].',\'blue\'],';
}
?>
]);
I tried also to add colors : ['blue','red'] and it changes the color of all the bars.
P.S : Note that the chart that I used is : Top X Chart Here is its link :
https://google-developers.appspot.com/chart/interactive/docs/gallery/barchart#top-x-charts
It seems that google.charts.Bar component does not support style role, but you could utilize google.visualization.BarChart component from corechart package instead to customize bar styles as demonstrated below.
Example
//google.load("visualization", "1.1", {packages:["bar"]});
google.load("visualization", "1.1", {packages:["corechart"]});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Opening Move', 'Percentage', { role: "style" }],
["King's pawn (e4)", 44, "#b87333"],
["Queen's pawn (d4)", 31, "silver"],
["Knight to King 3 (Nf3)", 12, "gold"],
["Queen's bishop pawn (c4)", 10, "color: #e5e4e2"],
['Other', 3,"green"]
]);
var options = {
title: 'Chess opening moves',
width: 900,
legend: { position: 'none' },
chart: { title: 'Chess opening moves',
subtitle: 'popularity by percentage' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Percentage'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('top_x_div'));
var chart = new google.visualization.BarChart(document.getElementById("top_x_div"));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="top_x_div" style="width: 900px; height: 500px;"></div>

Google Stacked Bar chart not displayed when data is omitted

I am trying to implement google charts in my project.
Where I want to display marks of last x tests on bar graph.
But the issue is, user can take any number of subjects for the test like only Math and History.So I only want to show that subjects in a bar chart.
I can not display 0 since "0" might infer that user got 0 marks in that subject. I just want to include those subjects which the user gives test for.
Is this possible in google Chart or any other library ?
Here is the code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Math', 'Science', 'History', 'Geography', { role: 'annotation' } ],
['#1', 10, 24, 20, ''],
['#2', 16, 22, 23, ''],
['#3', 28, 19, 29, '']
]);
var options = {
width: 600,
height: 400,
legend: { position: 'top', maxLines: 3 },
bar: { groupWidth: '75%' },
isStacked: true
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>
I tried morris.js, but I was unsuccessful.
Any help will be appreciated. Thanks!

Categories