i have one external JavaScript file which returns PHP response as JSON and i tried and check and its output is as desired i want to pass this data to datapoints of canvasjs
here is my json output checked and tested returning as desired by JavaScript
{ x: 1, y: 59 },{ x: 2, y: 93 },{ x: 3, y: 477 },{ x: 4, y: 506 }
being stored in sthtml variable.
here is that part of code
var html = '';
var sthtml = '';
var ndhtml = '', downlo;
for (var i = 0; i < data.length; i++) {
z = i + 1;
downlo = data[i];
html += '<tr id="' + i + '"><td>' + z + '</td></tr>';
sthtml += '' + downlo.stchart + '';
ndhtml += '' + downlo.ndchart + '';
}
$('#down-btn').html(html);
now i am passing this sthtml and ndhtml variable value to in page javascript with this ndhtml and sthtml. i tried ''+sthtml+'' and all other probable values but data is not returning and my graph is blank
<script type="text/javascript">
window.onload = function() {
var sthtml = [];
var ndhtml = [];
var chart = new CanvasJS.Chart("chartContainer", {
axisY: {},
data: [{
dataPoints: [sthtml]
}, {
dataPoints: [ndhtml]
}],
legend: {
cursor: "pointer",
itemclick: function(e) {
chart.render();
}
}
});
chart.render();
}
</script>
i think when i load the page that time its empty and later these values are populated when users submit form so we need to update these again through some push
any help will be useful how can i pass sthtml and ndhtml values in above JavaScript datapoints
Use this
<script type="text/javascript">
window.onload = function() {
var sthtml = '';
var ndhtml = '';
var chart = new CanvasJS.Chart("chartContainer", {
axisY: {},
data: [{
dataPoints: [sthtml]
}, {
dataPoints: [ndhtml]
}],
legend: {
cursor: "pointer",
itemclick: function(e) {
chart.render();
}
}
});
chart.render();
}
</script>
Inside onload function you are setting your variable as array but if you read the documentation on it requires a Joson data
data: [
{
type: "column", //change type to bar, line, area, pie, etc
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}
]
Inside the data object you need an dataPoints object, Inside the dataPoints object your json data should go. Try this I hope it will work.
Related
the issue I have now is that I'm trying to use objects in the "data" field of my Chartjs script. This is my code below:
<canvas id="QGL_Chart"></canvas>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<script>
var interval = window.onload = () => {
var selectedDate;
const buyPriceData = [];
const buyVolData = [];
const sellPriceData = [];
const sellVolData = [];
var ctx = document.getElementById("QGL_Chart").getContext('2d');
ctx.canvas.width = 934;
ctx.canvas.height = 400;
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Line A',
data: [{
x: 90,
y: 90
}, {
x: 20,
y: 96
}, {
x: 15,
y: 97
}]
},
{
label: 'Line B',
data: [{
x: 10,
y: 96
}, {
x: 20,
y: 95.8
}, {
x: 100,
y: 99
}]
}
]
},
options: {
title: {
display: true,
text: 'Equilibrum Graph',
fontSize: 18
},
legend: {
display: true,
position: "bottom"
},
scales: {
xAxes: [{
ticks: {
reverse: false,
// stepSize: 6,
min: 0
}
}]
}
}
});
function refreshCurveData () {
selectedDate = document.querySelectorAll(".buyclass .column-date.sorting_1")[1].textContent;
buyPriceTable = document.querySelectorAll(".buyclass td.column-price");
buyVolTable = document.querySelectorAll(".buyclass td.column-volume");
sellPriceTable = document.querySelectorAll(".sellclass td.column-price");
sellVolTable = document.querySelectorAll(".sellclass td.column-volume");
let i = 0;
do {
var buyPriceData1 = buyPriceTable[i].textContent;
var buyVolData1 = buyVolTable[i].textContent;
var sellPriceData1 = sellPriceTable[i].textContent;
var sellVolData1 = sellVolTable[i].textContent;
buyPriceData[i] = `{x: ${buyPriceData1}, y: ${buyVolData1}}`
sellPriceData[i] = `{x: ${sellPriceData1}, y: ${sellVolData1}}`
//buyPriceData[i] = buyPriceData[i].replace(/"/g, "");
//sellPriceData[i] = sellPriceData[i].replace(/"/g, "");
// buyPriceData.push ({ x: buyPriceData1, y: buyVolData1 });
// sellPriceData.push ({ x: sellPriceData1, y: sellVolData1 });
i++;
}
while ( document.querySelectorAll(".column-date.sorting_1")[i].textContent == selectedDate && i < 9);
}
setInterval(() => {
refreshCurveData();
myChart.update();
},2500);
};
</script>
When I replace the codes in the "data" fields with buyPriceData and sellPriceData respectively, the graph does not visualize, I also tried doing:
data: {
datasets: [{
label: 'Line A',
data: Object.values(buyPriceData)
},
{
label: 'Line B',
data: Object.values(sellPriceData)
}
]
},
But I still have the same problem, please can someone help me with this?
I've created a pen here: https://codepen.io/scottfranc/pen/BaLGwZK
Thank you.
it looks like you are saving a String in buyPriceData. It looks like it should be an object
Maybe try this:
buyPriceData[i] = { x: buyPriceData1, y: buyVolData1 };
and then do the same for sellPriceData
I need to plot some information that the X-axis is the time and the Y-axis is the a numerical value. The structure is similar to the next table,
Name Date Result
N1 9:00 88
N1 9:10 84
N1 9:16 83
N1 9:23 83
N1 9:29 85
N2 9:03 87
N2 9:07 87
N2 9:18 87
N2 9:25 86
N2 9:29 86
Thus, what I need with this example, are two independent lines that each one work with it data.
To show this info I'm using chart.js. My first idea was to use the scatter type graph, but this is not possible because it only works with numerical values. Therefore, I thought about using the line type graph, but the problem with this is that by default you can only define a single label and how you can see I need each information to be independent since they don't have to match the hours.
Is it possible to add another label? I've tried to define two lists but it doesn't work and I don't know how to deal with it.
let ctx = document.getElementById("my_chart").getContext("2d");
my_chart = new Chart(ctx, {
type: 'line',
data: {
labels: [
['9:00','9:10','9:16','9:23','9:29'],
['9:03','9:07','9:18','9:25','9:29']
],
datasets: [{
data: [88,84,83,83,85],
label: "N1",
borderColor: "#8e5ea2",
fill: false
}, {
data: [87,87,87,86,86],
label: "N2",
borderColor: "#c45850",
fill: false
}]
},
options: {
title: {
display: true,
text: 'Info'
}
}
});
EDIT: My modifications with the help of #alonas and #HeadhunterKev
This is what I have now, is not working I suppose the format is wrong but I don't know what. Maybe I need seconds? Probably is a silly question but I'm lost with this...
var sData = {
datasets: [{
label: 'Dataset1',
data: [{
x: '09:00',
y: 88
}, {
x: '09:10',
y: 89
}, {
x: '09:13',
y: 86
}, {
x: '09:23',
y: 86
}, {
x: '09:26',
y: 85
}, {
x: '09:29',
y: 83
}]
}, {
label: 'Dataset2',
data: [{
x: '09:02',
y: 88
}, {
x: '09:13',
y: 89
}, {
x: '09:14',
y: 86
}, {
x: '09:20',
y: 86
}, {
x: '09:24',
y: 85
}, {
x: '09:29',
y: 83
}]
}]
}
sData.datasets[0].data = formatData(sData.datasets[0].data)
sData.datasets[1].data = formatData(sData.datasets[1].data)
function formatData(oldData) {
var newData = []
for (var i = 0; i < oldData.length; i++) {
var currentData = {}
currentData.x = moment(oldData[i].x, "hh:mm").format('HH:mm')
currentData.y = oldData[i].y
newData.push(currentData)
}
return newData
}
var data = sData
var options = {
responsive: true,
scales: {
xAxes: [{
type: 'time',
}]
},
tooltips: {
callbacks: {
title: function(tooltipItem, data){
return moment(tooltipItem[0].label).format('hh:mm')
}
}
}
}
var ctx = document.getElementById('bateria_graf');
let chart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
Can somebody help me? Thank you very much.
You can provide data as a list of x,y:
datasets: [{
data: [{y:88,x:`${timestamp of 9:00}` },...],
...
}, {
data: [{y:87, x:`${timestamp of 9:03}`},...],
...
}]
like here https://www.chartjs.org/docs/latest/charts/line.html#point
And then in options define how to display the x value (timestamp) as hour:minutes
{
scales: {
xAxes: [{
ticks: {
callback = (label, index, labels) => {
return moment.unix(label).format('HH:mm');
}
}
}]
}
}
I created a webpage where some numbers are displayed in real time. The data is sent from a Python Flask script to my JavaScript frontend using SocketIO.
I'm now trying to show this numbers on a real time chart, and for that i'm using Apexcharts. The problem is that I'm not able to put on the chart what I need. I'm not getting any error at all, the chart won't work or display everything awfully.
As you can see, the data received from my socket is stored on numbers_received.
$(document).ready(function() {
//connect to the socket server.
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
var numbers_received = [];
//receive details from server
socket.on('newnumber', function(msg) {
console.log("Received" + msg.number);
//maintain a list of ten numbers
if (numbers_received.length >= 1) {
numbers_received.shift()
}
numbers_received.push(msg.number);
numbers_string = '';
for (var i = 0; i < numbers_received.length; i++) {
numbers_string = numbers_string + '<p>' + numbers_received[i].toString() + '</p>';
}
s
$('#log').html(numbers_string);
});
/*
// this function will generate output in this format
// data = [
[timestamp, 23],
[timestamp, 33],
[timestamp, 12]
...
]
*/
var lastDate = 0;
var data = [];
function getDayWiseTimeSeries(baseval, count, yrange) {
var i = 0;
while (i < count) {
var x = baseval;
var y = numbers_received;
data.push({
x,
y
});
lastDate = baseval
baseval += 86400000;
i++;
}
}
getDayWiseTimeSeries(new Date('11 Feb 2017 GMT').getTime(), 10, {
min: 10,
max: 90
})
function getNewSeries(baseval, yrange) {
var newDate = baseval + 86400000;
lastDate = newDate
data.push({
x: newDate,
y: numbers_received
})
}
function resetData() {
data = data.slice(data.length - 10, data.length);
}
var options = {
chart: {
height: 350,
type: 'line',
animations: {
enabled: true,
easing: 'linear',
dynamicAnimation: {
speed: 2000
}
},
toolbar: {
show: false
},
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
series: [{
data: data
}],
title: {
text: 'Dynamic Updating Chart',
align: 'left'
},
markers: {
size: 0
},
xaxis: {
type: 'datetime',
range: 777600000,
},
yaxis: {
max: 100
},
legend: {
show: false
},
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
var dataPointsLength = 10;
window.setInterval(function() {
getNewSeries(lastDate, {
min: 10,
max: 90
})
chart.updateSeries([{
data: data
}])
}, 2000)
// every 60 seconds, we reset the data
window.setInterval(function() {
resetData()
chart.updateSeries([{
data
}], false, true)
}, 60000)
});
need to wait for socket.on to finish, before drawing the chart.
socket.on is asynchronous, which means all the code after that section,
will run before socket.on is finished, unless by chance socket.on runs really quickly.
try something similar to following setup (see drawChart)...
$(document).ready(function() {
//connect to the socket server.
var socket = io.connect('http://' + document.domain + ':' + location.port + '/test');
var numbers_received = [];
var lastDate = 0;
var data = [];
//receive details from server
socket.on('newnumber', function(msg) {
console.log("Received" + msg.number);
//maintain a list of ten numbers
if (numbers_received.length >= 1) {
numbers_received.shift()
}
numbers_received.push(msg.number);
numbers_string = '';
for (var i = 0; i < numbers_received.length; i++) {
numbers_string = numbers_string + '<p>' + numbers_received[i].toString() + '</p>';
}
$('#log').html(numbers_string);
drawChart();
});
function drawChart() {
getDayWiseTimeSeries(new Date('11 Feb 2017 GMT').getTime(), 10, {
min: 10,
max: 90
})
var options = {
chart: {
height: 350,
type: 'line',
animations: {
enabled: true,
easing: 'linear',
dynamicAnimation: {
speed: 2000
}
},
toolbar: {
show: false
},
zoom: {
enabled: false
}
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
series: [{
data: data
}],
title: {
text: 'Dynamic Updating Chart',
align: 'left'
},
markers: {
size: 0
},
xaxis: {
type: 'datetime',
range: 777600000,
},
yaxis: {
max: 100
},
legend: {
show: false
},
}
var chart = new ApexCharts(
document.querySelector("#chart"),
options
);
chart.render();
var dataPointsLength = 10;
window.setInterval(function() {
getNewSeries(lastDate, {
min: 10,
max: 90
})
chart.updateSeries([{
data: data
}])
}, 2000)
// every 60 seconds, we reset the data
window.setInterval(function() {
resetData()
chart.updateSeries([{
data
}], false, true)
}, 60000)
}
function getDayWiseTimeSeries(baseval, count, yrange) {
var i = 0;
while (i < count) {
var x = baseval;
var y = numbers_received;
data.push({
x,
y
});
lastDate = baseval
baseval += 86400000;
i++;
}
}
function getNewSeries(baseval, yrange) {
var newDate = baseval + 86400000;
lastDate = newDate
data.push({
x: newDate,
y: numbers_received
})
}
function resetData() {
data = data.slice(data.length - 10, data.length);
}
});
I am trying to create a line plot from the json response from a webApi. I would like to create a time point dataset which looks like below:
var adddata = {
datasets: [{
label: "a",
backgroundColor: "rgba(255,0,0,0.5)",
fill: false,
data: [{
x: newDateString(0),
y: 22
}, {
x: newDateString(2),
y: 25
}, {
x: newDateString(4),
y: 12
}, {
x: newDateString(5),
y: 22
}],
}, {
label: "b",
backgroundColor: "rgba(0,255,0,0.5)",
fill: false,
data: [{
x: newDate(0),
y: 34
}, {
x: newDate(1),
y: 22
}, {
x: newDate(4),
y: 2
}, {
x: newDate(5),
y: 13
}]
}]
};
Now if I have a json which looks like:
{"Values":{"2018-01-17 09:24:34":"0","2018-01-17 09:24:31":"0","2018-01-17 09:24:33":"0","2018-01-17 09:24:35":"0"}}
Would it be possible to create a data set defining individual points?
You can parse your JSON string and transform resulting json object to dataset like below:
var json_str = '{"Values":{"2018-01-16 09:24:34":"10","2018-01-16 19:24:31":"5","2018-01-17 09:24:33":"8","2018-01-18 09:24:35":"9"}}'
var json = JSON.parse(json_str);
var data = [];
for (var d in json.Values) {
console.log(d, json.Values[d]);
data.push({
x : new Date(d),
y : json.Values[d]
})
}
var dataset = {
label : "c",
backgroundColor : "rgba(0,0,255,0.5)",
borderColor : 'green',
fill : false,
data : data
};
// add to existing datasets
adddata.push(dataset);
So this is the result: https://jsfiddle.net/beaver71/mfvc9p9x/
I' am using http://canvasjs.com/ to make a chart for my website. I want to create a dynamic dataPoints using the for loop. The dataPoints will be used a variable to the canvasjs function to plot the chart. Below are my sample data and my code.
Sample:
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55},
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14}
]
}
My current code
This code doesn't throw any error. All I see on the screen is just white area. All the values are passed correcting. I' am guess its the way I have structured the DataPoints. Please help.
DataPoints = [];
for (year = 1; year <= years; year++){
inflatedClosing = $('#lookup-table-preserved #row-' + year + ' .inflated-closing').text();
if( year === years ){
DataPoints.push({x: year, y: inflatedClosing});
} else {
DataPoints.push({x: year, y: inflatedClosing});
}
}
It should look like this
Here you have a working example with all the info you give:
var DataPoints = [], years = 3;
for (var year = 1; year <= years; year++){
var inflatedClosing = parseInt($('#lookup-table-preserved #row-' + year + ' .inflated-closing').text(), 10);
DataPoints.push({x: year, y: inflatedClosing, label : year});
}
//console.log(DataPoints);
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",//theme1
title:{
text: "Title"
},
animationEnabled: true,
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "line",
dataPoints: DataPoints
}
]
});
chart.render();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="lookup-table-preserved">
<ul id="row-1">
<li class="inflated-closing">50</li>
</ul>
<ul id="row-2">
<li class="inflated-closing">100</li>
</ul>
<ul id="row-3">
<li class="inflated-closing">200</li>
</ul>
</div>
<div id="chartContainer" style="height: 300px; width: 100%; margin-top: 20px;"></div>