I have two codes, both generate a line chart. However, the first one doesn't use mysql datasource, it uses random math generated datapoints. But it uses a refresh interval and thus is live.
The second code does in fact use a mysql datasource and displays the data in my database in the line-chart. However it is not live, because it does not it has not refresh-interval function.
I was trying to transfer the refresh-Interval / chart-update code parts of the first code to my second code that is not live but uses a real data source.
Here is my live code, with random datapoints:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">`
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer2",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
This is my code of the static line chart (not live) but uses real data source:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">`
</script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
chart.render();
});
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
This is what I have tried so far:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
var dataPoints = [];
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
};
}
if (dataPoints.length > dataLength)
{
dataPoints.shift();
}
chart.render();
)};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
But it keeps saying
Unexpected token ')' at line 42
chart.render();
)};
I am pretty embarrassed but I can't find the solution due to all the bracelets/parenthesizes. I have tried everything. With ) and without } but nothing seems to deliver.
If this is solved, will the chronological positions of the code be alright?
EDIT: FIRST PROBLEM SOLVED, NEW PROBLEM: JS POSITIONING
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript">
$().ready(function () {
$.getJSON("arduino_data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
var dataPoints = [];
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
};
}
if (dataPoints.length > dataLength)
{
dataPoints.shift();
}
chart.render();
});
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(updateChart, updateInterval);
});
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
output:
Can't find variable: updateChart
You used )}; instead of });
also at the end of your JS you used only } instead of });
also call your chart like
setInterval(updateChart, updateInterval);
and make sure your updateInterval is in the right function scope.
Here's how it should approximately look like:
jQuery(function ($) {
function updateChart( result ) { // move it here!!!
$.getJSON("arduino_data.php", function( result ){
var dataPoints = [];
var dataLength = 500; // number of dataPoints visible at any point
var updateInterval = 1000;
var chart = new CanvasJS.Chart("chartContainer",{ // new chart Object
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dataPoints
}]
});
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
if (dataPoints.length > dataLength){
dataPoints.shift();
}
chart.render();
});
}
// First read - Start
updateChart();
// Update chart after specified time.
setInterval(updateChart, updateInterval);
});
Related
This is usually a simple problem to solve with a global var. But nooooo...
All the code works, the csv is read in, the arrays created with the correct values (x,y), a default graph is drawn, but the newPlot function vars are not acting like globals and are empty, so the plot is an empty default of 6x6 with no traces. The newPlot vars are globals. Is plotly.js different? Line 63 is the culprit. This code is pretty much a clone of: plotlyHover
<!DOCTYPE html>
<html lang="en" >
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<div id="myDiv"></div>
<div id="hoverinfo" style="margin-left:80px;"></div>
<!-- cloudcover.csv looks like this.
Time,CloudCover
2022-04-06 10:07:09,0
2022-04-06 11:07:18,100.0
2022-04-06 12:08:17,100.0
2022-04-06 13:09:16,96.0
2022-04-06 14:10:15,66.0
2022-04-06 15:11:14,7.0
-->
<script>
var traces = [];
var layout = {};
var config = {};
const CSV = "cloudcover.csv";
Plotly.d3.csv(CSV, function(rows) {
let x = [];
let y = [];
let row;
let i = 0;
while (i < rows.length) {
row = rows[i];
x.push(row["Time"]);
y.push(row["CloudCover"]);
i += 1;
};
traces = [{
x: x,
y: y,
line: {
color: "#387fba"
},
width: 16,
}];
layout = {
title: 'Cloudcover',
yaxis: {
range: [0, 100]
},
xaxis: {
tickformat: "%H:%M:%S"
}
};
config = {
responsive: true
};
});
Plotly.newPlot('myDiv', traces, layout, config, {
showSendToCloud: true
});
var myPlot = document.getElementById('myDiv')
hoverInfo = document.getElementById('hoverinfo')
myPlot.on('plotly_hover', function(data) {
var infotext = data.points.map(function(d) {
return (d.data.name + ': x= ' + d.x + ', y= ' + d.y.toPrecision(3));
});
hoverInfo.innerHTML = infotext.join('<br/>');
})
myPlot.on('plotly_unhover', function(data) {
hoverInfo.innerHTML = '';
});
</script>
</body>
</html>
I have written the following code:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = viewport" content ="width=device-width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content = "ie=edge">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<link rel ="stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>My Chart.js</title>
</head>
<body>
<div class = "container">
<canvas id="myChart"></canvas>
</div>
<script>
var c = [];
var randomNumber = Math.random()*190;
function getRandomDataPoint(x){
if (x == "x"){
var _return
return Math.random()*20;
}
else if (x == "y"){
return Math.random()*10 + randomNumber;
}
else{
}
}
var xPoints = [];
var yPoints = [];
var storage = [];
for(var i=0;i<100;i++)
{
xPoints[i] = Math.random()*20;
yPoints[i] = Math.random()*10 + randomNumber;
x = xPoints[i];
y = yPoints[i];
var json = {x: x, y: y};
storage.push(json);
}
var concatenatedArray = xPoints.concat(yPoints);
let myChart = document.getElementById('myChart');//.getContext('2d');
Chart.defaults.global.defaultColor = '#000000';
let massPopChart = new Chart(myChart, {
type: 'scatter',
data: {
datasets: [{label: 'Data Set', data: [storage]}],
},
options: {
scales: {
yAxes: [{
ticks: {
max: 200,
min: 0,
beginAtZero:true
},
}]
}
}
});
</script>
</body>
</html>
What I would like for this code to do is take 100 random data points and plot them using the for-loop depicted in the code. The issue is the current set of code does create the axis however no data appears to be plotted.
Thank you for any help.
Best Regards
The problem is in how you pass your data values to Chart.js on this line:
datasets: [{label: 'Data Set', data: [storage]}],
Specifically, data is supposed to be an array of objects. Because you have added the square brackets ([]) you are passing an 'array of array of objects'.
The problem can be fixed simply by removing the brackets:
data: storage
window.onload = function() {
var dataPoints = [];
// fetching the json data from api via AJAX call.
var X = [];
var Y = [];
var data = [];
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', ' https://api.myjson.com/bins/cixax', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
}
xobj.send(null);
}
loadJSON(function(response) {
var response;
var field = JSON.parse(response);
var values = [];
//Iterating and storing leads & visits in a variable.
var $this = field;
for (var key in $this) {
if ($this.hasOwnProperty(key)) {
var data = $this[key].dates;
for (var val in data) {
values.push({
"X": data[val].visits,
"Y": data[val].leads
});
}
}
}
dataPoints = ({
"values": values
});
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Log Scale on Axis Y - Workaround using Linear Axis"
},
axisY: {
//valueFormatString: "0.## E0",
title: "In log scale",
labelFormatter: function(e) {
var lable = Math.pow(10, e.value);
if (lable >= 1000)
lable = CanvasJS.formatNumber(lable / 1000) + "k";
else
lable = CanvasJS.formatNumber(lable);
return lable;
},
interval: 1,
includeZero: false
},
toolTip: {
contentFormatter: function(e) {
var content = "Data Values";
for (var i = 0; i < e.entries.length; i++) {
content += "</br>" + e.entries[i].dataPoint.x + " : ";
content += CanvasJS.formatNumber(Math.round(Math.pow(10, e.entries[i].dataPoint.y)));
}
return content;
}
},
data: [{
type: "line",
dataPoints: []
}]
}); convertToLog(chart.options.data); chart.render();
function convertToLog(data) {
var dataPoints;
for (var j = 0; j < data.length; j++) {
dataPoints = data[j].dataPoints;
for (var i = 0; i < dataPoints.length; i++) {
dataPoints[i].y = Math.log10(dataPoints[i].y);
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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>
Here I am trying to draw the graph using canvasjs. I am getting the input from the external API using an AJAX call. And storing the variables X and Y in the array. Providing that as an input to that canvasjs library for drawing the graph. But I am not able to draw the graph. The above snippet is the one I have done.
The Chart wasn't getting rendered because the render method gets called before the data actually is loaded.
"x" & "y" should be in small instead of capital. The graph looks scrambled because the X Values in your JSON are not sorted.
Since the library now supports Logarithmic Scale on Y-Axis, you can use that instead of the work around.Here's a documentation link.
window.onload = function() {
//var dataPoints = [];
// fetching the json data from api via AJAX call.
var X = [];
var Y = [];
var data = [];
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'https://api.myjson.com/bins/cixax', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
}
xobj.send(null);
}
loadJSON(function(response) {
var response;
var field = JSON.parse(response);
var values = [];
//Iterating and storing leads & visits in a variable.
var $this = field;
for (var key in $this) {
if ($this.hasOwnProperty(key)) {
var data = $this[key].dates;
for (var val in data) {
values.push({
"x": data[val].visits, // Should be "x" & "y"
"y": data[val].leads
});
}
}
}
//dataPoints = ({
// "values": values
//});
// Update the dataPoints & render the chart
// x values need to be in sorted order
chart.options.data[0].dataPoints = values;
chart.render();
});
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Log Scale on Axis Y - Workaround using Linear Axis"
},
axisY: {
//valueFormatString: "0.## E0",
title: "In log scale",
labelFormatter: function(e) {
var lable = Math.pow(10, e.value);
if (lable >= 1000)
lable = CanvasJS.formatNumber(lable / 1000) + "k";
else
lable = CanvasJS.formatNumber(lable);
return lable;
},
interval: 1,
includeZero: false
},
toolTip: {
contentFormatter: function(e) {
var content = "Data Values";
for (var i = 0; i < e.entries.length; i++) {
content += "</br>" + e.entries[i].dataPoint.x + " : ";
content += CanvasJS.formatNumber(Math.round(Math.pow(10, e.entries[i].dataPoint.y)));
}
return content;
}
},
data: [{
type: "line",
dataPoints: []
}]
}); //convertToLog(chart.options.data); chart.render();
function convertToLog(data) {
var dataPoints;
for (var j = 0; j < data.length; j++) {
dataPoints = data[j].dataPoints;
for (var i = 0; i < dataPoints.length; i++) {
dataPoints[i].y = Math.log10(dataPoints[i].y);
}
}
}
}
<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>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
I used this ,to multiply doughnut chart according as array(arr) has,but it can't change to object,(data has string type).So chart doesn't appear here..,how fix it
var arr=['HTML','CSS','JS'],i,data;
data ='[';
for(i=0;i<arr.length;i++){
if(i==arr.length-1){
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]}';
}
else{
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]},';
}
}
data += ']';
var dat = data;
window.onload = function () {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat,{
responsive: true,
});
};
//want like this
dat =[{value:"300",color:"#fff",highlight:"#aaa",label:"HTML"},
{value:"200",color:"#fff",highlight:"#aaa",label:"CSS"}];
You are creating your array as a String.
You need to create an array of objects [{},{},{}].
The method used to INSERT a new object in an array is PUSH().
Check the fiddle. Now it´s working OK (move the mouse on the screen to see the chart is there (you will only see it when mouse is over it):
window.onload = function() {
var arr = ['HTML', 'CSS', 'JS'],
i, data;
data = [];
for (i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
} else {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
}
}
var dat = data;
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat, {
responsive: true,
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/nnnick/Chart.js/master/Chart.js"></script>
<canvas id="chart-area"></canvas>
The problem I am encountering is that when I click to view the diagram via JQuery event click, the diagram works fast and smoothly, but if I double click or perhaps click 10 times, for each click the diagrams runs slower and slower. That is to say the click is dependend on the diagram performance. I believe the $.getscript() is causing this low performance, or poor JQuery code..
JQuery event below is responsible for displaying the diagram. Keep in mind that the user has the oppertunity to navigate between the diagrams, they can only view one diagram once.
$('[data-row]').on('click', function() {
var row = $(this).attr('data-row');
$('.active').removeClass('active'); // Displaye:none
$('#table' + row).addClass('active'); // Display:block
if(row == 1){
$.getScript("diagram1.js"); // Display diagram1
} else {
}
});
This is diagram1.js.
(function (){
$(document).ready(function(){
var dps = []; // data
var chart = new CanvasJS.Chart("diagram1 ",
{
title:{
text: "Exhaust Temperature"
data: [
{
type: "spline",
name: "Temp Cylinder 1",
showInLegend: "true",
legendText: "Temp Cylinder 1",
dataPoints: dps1
}
});
var xVal = 0;
var updateInterval = 50;
var dataLength = 50;
var updateChart = function (count) {
count = count || 1;
for (var j = 0; j < count; j++) {
dps.push({
x: xVal,
y: EXTS[1]
});
xVal++;
};
if (dps.length > dataLength )
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
});
}());