I am trying to draw CanvasJs chart using data from json file but for some reason it does not work.
The data which I am trying to display are data which is in json file represented as number "####" and value "#"
Please take a look at the code below.
<!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: new Year(data[i].date),
y: data[i].value
});
}
chart.render();
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", addData);
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
First you need to call the json, $.getJson gives a callback, so once the api gives the data you need to create the dataPoints, once its created create the chart.
I hope the below solution will solve the issue.
Note: If required you can add a loader for the mean time while its loading , so the user will know that some thing is loading
const chartCreation = (data) => {
$("#chartContainer").CanvasJSChart({
animationEnabled: true,
theme: "light2",
title: {
text: "Years"
},
axisY: {
title: "Value",
titleFontSize: 24
},
data: [{
type: "column",
yValueFormatString: "# Value",
dataPoints: dataPoints
}]
});
}
let dataPoints = [];
const addData = (data) => {
dataPoints = data[1].filter(obj => +(obj.date) >= 2010 && +(obj.date) <=2018
).map(obj => ({x: +(obj.date),
y: obj.value ? obj.value : 0}))
// once we have the data pass it to chart creation
// function
chartCreation(dataPoints);
}
$.getJSON("https://api.worldbank.org/v2/countries/gbr/indicators/UIS.FOSEP.56.F600?format=json", (data) =>{
// pass the data to function
addData(data);
});
return{
}
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Updated
As per the comment, first you can array.filter , once you filter you will get a new array where you can return the properties whatever that you want. using array.map to return what ever the properties.
Related
I am trying to plot a graph using chart.js where y-axis values are numbers and x-axis values are strings. I have given the code that i have written, but it does not plot the string values.
Appreciate your help.
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
x: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</html>
For your case you should supply label property not x value and also i believe you should use column charts for this purpose.
You might see some labels not showing up.You can either set the angle or increase the width of chart to make it visible.
Try running this snippet
window.onload = function() {
var dataPoints7 = [];
var chart7 = new CanvasJS.Chart("chartContainer7", {
animationEnabled: true,
theme: "light2",
title: {
text: "Cases in States"
},
axisY: {
title: "Cases",
titleFontSize: 24
},
axisX: {
labelAngle: 180
},
data: [{
type: "line",
yValueFormatString: "#,### Cases",
dataPoints: dataPoints7
}]
});
fetch("https://api.covid19india.org/data.json", {
"method": "GET"
})
.then(function(response) {
return response.json();
})
.then(function(data) {
for (var i = 1; i < data.statewise.length; i++) {
dataPoints7.push({
label: data.statewise[i].state,
y: parseInt(data.statewise[i].confirmed)
});
}
chart7.render();
});
}
<!DOCTYPE html>
<html lang="en">
<div id="chartContainer7" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</html>
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 3 years ago.
I am new to Javascript and ran into a problem I can't resolve.
I wanted to rewrite an example with jquery into pure Javascript.
I don't understand why this doesn't work.
Why is the variable "vorlauf" empty outside the function?
Isn't it a global variable?
I attached a picture of the console output.
Not working as expected (tried to omit every clutter...):
<!DOCTYPE HTML>
<html>
<head>
<script>
let vorlauf = new Array();
let getJSON = function (name) {
fetch(name + ".json")
.then(response => response.json())
.then(parsed => {
console.log(parsed.length, parsed)
for (let i = 0; i < parsed.length; i++) {
vorlauf.push({
x: new Date(parsed[i].date + " " + parsed[i].time),
y: Number(parsed[i].temp) / 1000
})
}
});
}
getJSON("vorlauf")
console.log("Nach Aufruf getJSON " + vorlauf.length)
</script>
</head>
<body>
</body>
</html>
Works as expected (included everything):
!DOCTYPE HTML>
<html>
<head>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX:{
valueFormatString: "YYYY-MM-DD hh:mm:ss" ,
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for(let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
The json data:
[{"date": "2020-02-22", "temp": "39937", "time": "09:28:59"}, {"date": "2020-02-22", "temp": "39937", "time": "09:29:21"}]
picture of the debug output of Firefox
Please place all javascript above .
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div id="chartContainer" style="height: 70%; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
window.onload = function() {
let vorlauf = [];
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
title: {
text: "Vorlauf"
},
axisY: {
title: "Grad",
titleFontSize: 24
},
axisX: {
valueFormatString: "YYYY-MM-DD hh:mm:ss",
labelAngle: -50
},
data: [{
name: "Vorlauf",
showInLegend: true,
type: "spline",
dataPoints: vorlauf
}]
});
$.getJSON("http://localhost/vorlauf.json", function(data) {
for (let i = 0; i < data.length; i++) {
vorlauf.push({
x: new Date(data[i].date + " " + data[i].time),
y: Number(data[i].temp) / 1000
});
}
chart.render();
})
}
</script>
I'm using Canvasjs to create a candlestick chart. The values are coming from PHP and I use JSON-encode to convert to the javascript array. I recreate the javascript array in the same format as the example, which is this
dataPoints=[{x: new Date(2012,01,01),y:[5198, 5629, 5159, 5385]}]
But the canvas is blank? Here is my code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array("5198", "5629", "5159", "5385"));
$chart_array[] = array("x"=>"2012-01-02","y"=>array("5366", "5499", "5135", "5295"));
$chart_array = json_encode($chart_array);
?>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
console.log(new_array);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
console.log show the array exists. Why is a blank canvas showing? How do I solve?
Y-value in your code seems to be string, which should be numeric. Even if you are storing it as string, parsing it to number before passing it to chart-options will work fine.
Here is the working code:
<?php
$chart_array[] = array("x"=>"2012-01-01","y"=>array(5198, 5629, 5159, 5385));
$chart_array[] = array("x"=>"2012-01-02","y"=>array(5366, 5499, 5135, 5295));
$chart_array = json_encode($chart_array);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var resultArray = <?php echo $chart_array; ?>;
var new_array = [];
jQuery.each(resultArray, function(index, item) {
new_array.push({ x: new Date(item.x), y: item.y });
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Candle Stick Chart"
},
zoomEnabled: true,
axisY: {
includeZero: false,
title: "Prices",
prefix: "$ "
},
axisX: {
interval: 2,
intervalType: "month",
valueFormatString: "MMM-YY",
},
data: [
{
type: "candlestick",
dataPoints: new_array
}
]
});
chart.render();
}
</script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
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.
First time poster, and still relatively new to javascript... I am trying to figure out how to reflect information from a php file to a canvasjs file.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 60, x: 2 },
]
},
{
type: 'line',
dataPoints: [
{ label: "2014/1/2", y: 0, x: 2 },
]
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Instead of the labels and datapoints etc, I want information from a php file (or how to do it to any type of file) to be collected then displayed into this canvasjs file.
Is there a way to do this?
Sorry if I'm not clear, I really appreciate any help I can get :)
Thanks!
One way would be to make the file you pasted a PHP file, then use PHP in it:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
?>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
},
{
type: 'line',
dataPoints: <?php echo json_encode($dataPoints) ?>
}
]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
Another way would be to create a PHP file that returns the data, and make an AJAX request:
data.php:
<?php
$dataPoints = [ [ "label" => "2014/1/2", y => 0, x => 2 ] ];
echo json_encode($dataPoints);
ui.html:
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"> </script>
<script type="text/javascript">
window.onload = function () {
var request = new XMLHttpRequest();
request.onload = function () {
var dataPoints = JSON.parse(request.responseText);
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "My First Chart in CanvasJS"
},
data: [
{
type: 'line',
dataPoints: dataPoints
},
{
type: 'line',
dataPoints: dataPoints
}
]
});
chart.render();
};
request.open('GET', 'data.php', true);
request.send();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>