CanvasJS Column chart with external json data not loading - canvasjs

Im trying to load this column chart with external data in Json format from a file
I have a jsfiddle with what i have so far.
Thanks for any help.
http://jsfiddle.net/t9n4d8z4/1/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({
label: result[i].label,
y: parseInt(result[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: result
}]
});
chart.render();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

json format was not handled properly.
Here is the working fiddle : http://jsfiddle.net/canvasjs/t9n4d8z4/3/
$(document).ready(function() {
var dataPoints = [];
$.getJSON("https://api.myjson.com/bins/1kfs1", function(result) {
for (var i = 0; i <= result.dataPoints.length - 1; i++) {
dataPoints.push({
label: result.dataPoints[i].label,
y: parseInt(result.dataPoints[i].y)
});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [{
type: "column",
dataPoints: dataPoints
}]
});
chart.render();
});
});
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

Related

CanvasJS changing chart-type based on drop-down value

I want to change the chart-type based on the drop-down value. I had tried and followed the example but it still unable to work. I'm not sure which part that i had missed. I am using JavaScript Charts & Graphs from JSON Data Using AJAX. The code below:
<script src="../js/custom.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/>
<script>
window.onload = function () {
var dataPoints = [];
$.getJSON( "<?php echo $url; ?>", function( json ) {
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
})
.done(function(){
alert("Completed");
})
.fail(function(e){
console.log('error:');
console.error(e);
})
.always(function(){
alert("always runs");
});
}
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
</script>
Drop-down list:
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>
Thank you in advance.
It just seems like variable scope issue, you are creating chart inside AJAX but trying to access it outside during changing the chart type, it would have thrown error in Browser Console. I would suggest you to do it outside AJAX and update just dataPoints inside AJAX.
Here is the updated / working code (Sample JSON with just 1 dataPoint is stored in: https://api.myjson.com/bins/18hgaa):
var dataPoints = [];
var chart;
$.getJSON("https://api.myjson.com/bins/18hgaa", function(json){
for (var i = 0; i < json.dates.length; i++) {
dataPoints.push({
x: new Date(json.dates[i]),
y: json.values[i]
});
}
}).done(function(){
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
exportEnabled: true,
theme: "dark2",
title: {
text: "REPORT"
},
axisY: {
title: "Qty"
},
data: [{
type: "column",
//indexLabel: "{y}", //Shows y value on all Data Points
yValueFormatString: "#,### Units",
indexLabelFontColor: "#5A5757",
indexLabelPlacement: "outside",
dataPoints: dataPoints
}]
});
chart.render();
});
var chartType = document.getElementById('chartType');
chartType.addEventListener( "change", function(){
for(var i = 0; i < chart.options.data.length; i++){
chart.options.data[i].type = chartType.options[chartType.selectedIndex].value;
}
chart.render();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
<select id="chartType" class="form-control" name="chartType">
<option value="column">Column</option>
<option value="line">Line</option>
<option value="bar">Bar</option>
<option value="pie">Pie</option>
<option value="doughnut">Doughnut</option>
</select>

javascript canvasjs Get data points dynamically from file.txt

Objective:
I want to get data from file.txt thats is saved local in /var/www/html/file.txt and use it for the doughnut chart on my webpage dynamically on a interval of 2 seconds
file.txt only has one entry and looks like:
34
the javascript i have tried:
$.get("file.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({y: parseInt(allLines[i])});
x += .25;
}
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "doughnut",
dataPoints : dataPoints,
}]
});
chart.render();
});
}
Entire html looks like
<!DOCTYPE html>
<html>
<head>
<title>Chart using txtfile Data</title>
<script type="text/javascript" src="http://canvasjs.com/assets/script /jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : [function()
{
if(allLines.length > 0) {
for(var i=0; i< allLines.length; i++) {
xVal +=.25;
dataPoints.push({x : xVal, y: parseInt(allLines[i])});
}
}
}]
}]
});
chart.render();
},'text');
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
I believe something like this may work for you. You may have to use Firefox as Chrome doesn't like cross origin requests
First, dataPoints was undefined, I moved the code into a function inside dataPoints. I changed your variable name from x to xVal. Added the 'text' word so the $get knows what format it's reading and also there was an extra bracket it seemed. Give this a try.
$.get("graph.txt", function(data) {
var xVal = 0;
var allLines = data.split('\n');
var dps = [];
for(var i=0; i< allLines.length; i++) {
xVal +=.25;
dps.push({x : xVal, y: Number(allLines[i])});
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Chart using Text File Data"
},
data: [{
type: "line",
dataPoints : dps
}]
});
chart.render();
},'text');

D3 pie chart is not displaying for me

Hi I am trying to Display D3 pie chart but i am getting only legend symbols ...can someone please help me to display d3 pie chart for dynamic data display.it will not show any errors only legend symbols displayed pie chart is not displaying.
here is the html i am using
<script src="angularjs-nvd3-directives-master/examples/js/angular.js"></script>
<script src="angularjs-nvd3-directives-master/examples/js/d3.js"></script>
<script src="angularjs-nvd3-directives-master/examples/js/nv.d3.js"></script>
<script src="angularjs-nvd3-directives-master/dist/angularjs-nvd3-directives.js"></script>
<link href="angularjs-nvd3-directives-master/examples/stylesheets/nv.d3.css" rel="stylesheet" />
<style>
#chart svg {
height: 295px;
width:300px;
}
</style>
<div id="chart">
<svg></svg>
</div>
and the javascript code i am using is...I want to display pie chart for dynamic data.
$.ajax({
type: "POST",
url: "Assets.asmx/Statereport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
function OnSuccess(data, status) {
var myObject = JSON.parse(data.d);
var source = {
datatype: "json",
datafields: [
{ name: 'totsch' },
{ name: 'districtname' },
{ name: 'statename' }
],
localdata: myObject
};
var dataAdapter = new $.jqx.dataAdapter(source);
var ObjectIDs = [];
for (var i = 0; i < myObject.length; i++) {
ObjectIDs.push(myObject[i].statename);
}
var gridquerystr = ObjectIDs[0].toString();
nv.addGraph(function () {
var chart = nv.models.pieChart()
.x(function (d) { return d.label })
.y(function (d) { return d.value })
.showLabels(false);
d3.select("#chart svg")
.datum(myObject)
.transition().duration(1200)
.call(chart);
return chart;
});
please help me as soon as posssible..... or suggest me any opensource charts for displaying dynamic data using ajax json data . I am new to coding so please help
[![d3 pie chart][1]][1]
[1]: http://i.stack.imgur.com/ppqZf.jpg

How to handle mouseout event on DC range graph

I am using DC chart range filter. I want to handle mouse out event on range filter, so I can handle filter on mouse-out. I had used filter and post-redraw but when I use this there are multiple time event fire on single drag on range chart. I need only the last change event and I think a mouse out or mouse up event would be helpful. Can any one help me with how to use mouse up/mouse out event on range Chart?
chart.on('postRender', function() {
chart.select('.brush').on("mouseover", function() {
console.log('mouseover');
});
chart.select('.brush').on("mouseout", function() {
console.log('mouseout');
});
chart.select('.brush').on("mouseup", function() {
console.log('mouseup')
});
chart.select('.brush').on("click", function() {
console.log('click')
});
});
Working snippet below:
var data = [{
date: "2011-11-21",
total: 90
}, {
date: "2011-11-22",
total: 90
}, {
date: "2011-11-23",
total: 90
}, {
date: "2011-11-24",
total: 200
}, {
date: "2011-11-25",
total: 200
}];
var cf = crossfilter(data);
var timeDimension = cf.dimension(function(d) {
return new Date(d.date);
});
var totalGroup = timeDimension.group().reduceSum(function(d) {
return d.total;
});
var chart = dc.lineChart("#chart")
.width(400)
.height(200)
.x(d3.time.scale().domain(d3.extent(data, function(d) {
return new Date(d.date);
})))
.dimension(timeDimension)
.group(totalGroup)
.renderArea(true)
.brushOn(true);
chart.xAxis().ticks(4);
function caught(eventName) {
document.getElementById(eventName).className = 'bold';
setTimeout(function() {
document.getElementById(eventName).className = '';
}, 750);
}
chart.on('postRender', function() {
chart.select('.brush').on("mouseover", function() {
console.log('mouseover');
caught('mouseover');
});
chart.select('.brush').on("mouseout", function() {
console.log('mouseout');
caught('mouseout');
});
chart.select('.brush').on("mouseup", function() {
console.log('mouseup')
caught('mouseup');;
});
chart.select('.brush').on("click", function() {
console.log('click')
caught('click');;
});
});
chart.render();
<link href="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.2.0/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.11/crossfilter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dc/1.7.3/dc.js"></script>
<style>
.bold {
font-weight: bold;
}
</style>
<div id="chart"></div>
<div id="mouseout">mouseout</div>
<div id="mouseover">mouseover</div>
<div id="mouseup">mouseup</div>
<div id="click">click</div>

how to use the Dojo code in Enyo..?

I'm a new developer in Enyo(TouchPad). I would like to develop an app consisting some charts in it. so I'm trying to use Dojo framework libraries in Enyo.
Can anyone please help me in how to include the dojo code my application.
I'm posting my code, please have a look.
INDEX.HTML :
<!doctype html>
<html>
<head>
<title>Canvas Demo</title>
<script src="../../../../1.0/framework/enyo.js" type="text/javascript"></script>
<script src="lib/widget/Chart2D.js" type="text/javascript"> </SCRIPT>
<script src="lib/chart2D.js" type="text/javascript"> </SCRIPT>
<script src="lib/tom.js" type="text/javascript"> </SCRIPT>
</head>
<body>
<script type="text/javascript">
enyo.create({kind: "CanvasDemo"}).renderInto(document.body);
</script>
</body>
</html>
.Js file ::
enyo.kind({
name: "CanvasDemo",
kind: enyo.Control,
nodeTag: "canvas",
domAttributes: {
width:"300px",
height:"300px",
style: "border: 2px solid #000;"
},
// After the canvas is rendered
rendered: function() {
// I want to place the dojo code here to display a chart in the canvas.
}
});
DOJO CODE ::
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.Tom');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
var chart2 = new dojox.charting.Chart2D('chart2').
setTheme(dojox.charting.themes.Tom).
addPlot('default', {type: 'Pie', radius: 70, fontColor: 'black'}).
addSeries('Visits', chartData).
render();
var anim = new dojox.charting.action2d.MoveSlice(chart2, 'default');
chart2.render();
});
Please help me in how to modify the dojo code ,so that it can work in the enyo..
Thanks in Advance.
Regards,
Harry.
index.html :
<!doctype html>
<html>
<head>
<title>dojo</title>
<script src="C:\WebOs\Development\enyo\1.0\framework\enyo.js" type="text/javascript"></script>
<script type="text/javascript" src="C:\Users\pangulur\Downloads\dojo-release-1.6.1-src\dojo-release-1.6.1-src\dojo\dojo.js"></script>
/head>
<body>
<script type="text/javascript">
new enyo.Canon.graphs2().renderInto(document.body);
</script>
</body>
</html>
Source/Charts1.js :
enyo.kind({
name: "enyo.Canon.graphs2",
kind: enyo.Control,
components: [
{kind: "PageHeader", content: "bargraph"},
//{style: "padding: 10px", content: "Note: In the browser, you can press ctrl-~ to display the app menu."},
{kind: "Button", caption: "display graph", onclick: "displayGraph", flex: 1},
],
displayGraph: function() {
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.green');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
//create / swap data
var barData = [];
dojo.forEach(chartData,function(item) { barData.push({ x: item['y'], y: item['x'] }); });
var chart1 = new dojox.charting.Chart2D('chart1').
setTheme(dojox.charting.themes.PlotKit.green).
addAxis('x', { fixUpper: 'major', includeZero: false, min:0, max:6 }).
addAxis('y', { vertical: true, fixLower: 'major', fixUpper: 'major' }).
addPlot('default', {type: 'Columns', gap:5 }).
addSeries('Visits For February', chartData, {});
var anim4b = new dojox.charting.action2d.Tooltip(chart1, 'default');
var anim4c = new dojox.charting.action2d.Shake(chart1,'default');
chart1.render();
// var legend4 = new dojox.charting.widget.Legend({ chart: chart1 }, 'legend3');
});
}
});
Here I'm not sure about how to call the dojo code in enyo.
and
depends.js :
enyo.depends(
"source/charts1.js",
"lib/Chart2D.js",
"lib/widget/Chart2D.js",
"lib/blue.js",
"lib/dojo.js"
);
Now I'm getting the following errors :
error: Uncaught ReferenceError: dojo is not defined, Chart2D.js:1
[20110818-09:33:13.136736] error: Uncaught ReferenceError: dojo is not defined, widget/Chart2D.js:1
[20110818-09:33:13.138227] error: Uncaught ReferenceError: dojo is not defined, blue.js:1
[20110818-09:33:13.150707] error: Uncaught TypeError: Cannot read property 'graphs2' of undefined, index.html:10
It is working fine when I use it as a .HTML file with the same code in browser.
Chart.html :
<html>
<head>
<title>dojo</title>
<script type="text/javascript" src="C:\Users\pangulur\Downloads\dojo-release-1.6.1- src\dojo-release-1.6.1-src\dojo\dojo.js"></script>
</head>
<body>
<div id="chart1" style="width:260px;height:200px;"></div>
<script>
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.green');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
//create / swap data
var barData = [];
dojo.forEach(chartData,function(item) { barData.push({ x: item['y'], y: item['x'] }); });
var chart1 = new dojox.charting.Chart2D('chart1').
setTheme(dojox.charting.themes.PlotKit.green).
addAxis('x', { fixUpper: 'major', includeZero: false, min:0, max:6 }).
addAxis('y', { vertical: true, fixLower: 'major', fixUpper: 'major' }).
addPlot('default', {type: 'Columns', gap:5 }).
addSeries('Visits For February', chartData, {});
var anim4b = new dojox.charting.action2d.Tooltip(chart1, 'default');
var anim4c = new dojox.charting.action2d.Shake(chart1,'default');
chart1.render();
var legend4 = new dojox.charting.widget.Legend({ chart: chart1 }, 'legend3');
});
</script>
</body>
</html>
Please help me in working with this in Enyo.
Thanking You.
Kind Regards,
Harry.
I don't think you have to modify the Dojo code. In Enyo, you have to tell the framework where it has to look for included JS files. Yo do so editing the depends.js file.
The index.html:
<!doctype html>
<html>
<head>
<title>Canvas Demo</title>
<script src="../../../../1.0/framework/enyo.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
new enyo.Canon.graphs2().renderInto(document.body);
</script>
</body>
</html>
and depends.js:
enyo.depends(
"lib/dojo/dojo.js" ,
"source/charts1.js"
);
You'll have to copy everything Dojo needs to work (dojo, dojox, dijit) into lib, and check enyo paths.
I get a Dojo error when creating the new Chart2D object, and I'm not a Dojo expert to fix this. It's in the line:
var chart1 = new dojox.charting.Chart2D("simplechart");
I've modified your code:
enyo.kind({
name: "enyo.Canon.graphs2",
kind: enyo.Control,
components: [
{kind: "PageHeader", content: "bargraph"},
//{style: "padding: 10px", content: "Note: In the browser, you can press ctrl-~ to display the app menu."},
{kind: "Button", caption: "display graph", onclick: "displayGraph", flex: 1},
],
displayGraph: function() {
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.green');
/* JSON information */
var json = {
January: [12999,14487,19803,15965,17290],
February: [14487,12999,15965,17290,19803],
March: [15965,17290,19803,12999,14487]
};
/* build pie chart data */
var chartData = [];
dojo.forEach(json['January'],function(item,i) {
chartData.push({ x: i, y: json['January'][i] });
});
/* resources are ready... */
dojo.ready(function() {
//create / swap data
var barData = [];
dojo.forEach(chartData,function(item) { barData.push({ x: item['y'], y: item['x'] }); });
var chart1 = new dojox.charting.Chart2D("simplechart"); // HERE IS THE PROBLEM
chart1.setTheme(dojox.charting.themes.PlotKit.green);
chart1.addAxis('x', { fixUpper: 'major', includeZero: false, min:0, max:6 });
chart1.addAxis('y', { vertical: true, fixLower: 'major', fixUpper: 'major' });
chart1.addPlot('default', {type: 'Columns', gap:5 });
chart1.addSeries('Visits For February', chartData, {});
var anim4b = new dojox.charting.action2d.Tooltip(chart1, 'default');
var anim4c = new dojox.charting.action2d.Shake(chart1,'default');
chart1.render();
// var legend4 = new dojox.charting.widget.Legend({ chart: chart1 }, 'legend3');
});
}
});
The object doesn't get instantiated. Got null pointer :-(

Resources