amcharts: trying to dynamically add multiple datasets to javascript stockChart - javascript

I am using AmCharts for displaying some charts and I am trying to dynamically add the data from a series of JSON data sets which are acquired using jquery's getJSON
My question in short is, how do I loop through my various data sets creating dataSets for the charts using something like:
$.getJSON("GET NUMBER OF DATA SETS REQUIRED", function (locdata) {
$.each(locdata, function (i, item) {
$.getJSON("GET DATA FOR THIS DATASET", function (data) {
var dataSet = new AmCharts.DataSet();
dataSet.title = locdata[i].name;
dataSet.fieldMappings = [{
fromField: "takings",
toField: "takings"
}, {
fromField: "qty",
toField: "qty"
}];
dataSet.dataProvider = data; ;
dataSet.categoryField = "date";
)};
)};
)};
To explain what I am doing here:
Firstly, getting some JSON output from my database to determine how many record sets are required
Looping through the result from this to create recordsets
During each loop, the data is acquired by a second jQuery getJSON call to grab data based on the data required for this recordset
Creating an AmCharts Dataset
I can manually do this by explicitly coding to create each dataset individually and then doing
chart.dataSets = [dataSet0, dataSet1, dataSet2, dataSet3, dataSet4];
So I guess what I need to do is turn the whole of the code above into some kind of function which generates an array of datasets as per the line above?
I'm not sure how to do this with javascript though

you can simply push each data set to chart.dataSets array:
chart.dataSets.push(dataSet);

Related

Update stock price in anychart without re-plotting whole chart

I am playing with the Anychart stock candlestick chart which is very nice, in order to update the chart I use a setInterval function but it re-plots the entire chart which sucks because if I am zooming or something it resets and starts over obviously. Is there a way I can just update last price from the database every couple seconds without re-plotting the whole chart?
Current setInterval function to load chart:
setInterval(function() {
$.get('chart_data.php', function(data) {
$(".main_cont").replaceWith(data);
});
}, 2000);
My chart_data variable:
$chart_data .= "{'x':'".$open_time."','open': ".$open.",'high': ".$high.",'low': ".$low.",'close': ".$close."},";
chart_data.php file:
anychart.onDocumentReady(function() {
// create a data table
var table = anychart.data.table('x');
// add data
table.addData([<?php echo $chart_data;?>]);
// add data
//table.addData([ {'x':'08/09/2020 10:11','open': 11000,'high': 10000,'low': 8000,'close': 8500}]);
// create a stock chart
var chart = anychart.stock(true);
// create a mapping
var mapping = table.mapAs({
'date': 'date',
'open': 'open',
'high': 'high',
'low': 'low',
'close': 'close',
'fill': 'fill'
});
var plot = chart.plot(0);
// add a series using the mapping
chart.plot(0).candlestick(mapping).name();
// set container id for the chart
chart.container('container');
var series = chart.plot(0).candlestick(mapping);
chart.scroller().xAxis(false);
// initiate chart drawing
chart.draw();
});
I would like to replace the setInterval function with something that just replaces the last price data from the database to move the candle up or down, if a new record is added then draw the new candle. I have the script to update the candle or add a new candle I just cannot find a way to do it without re-drawing the whole chart.
You can use the functions for manipulating data to alter the chart.
You can use JS to fetch new data every two seconds, and use addData() to replace the existing data. If that still causes a complete refresh, you'll have to compare the difference between two arrays to determine the difference between the current data and newly fetched data, and use the insert, delete and update methods as described in the docs to alter just the changed data. However, this may still may result in a complete refresh.
You would use AJAX (from JS) to request updated data from a PHP script. The data gets returned to your JS. It's probably easiest to send/receive data in JSON format via jQuery.getJSON.
There's no need to recreate the chart or even reapply the whole data. The AnyStock API provides all you need to update a part of the data. The series will be updated automatically.
For this purpose, you can use addData() function. It replaces all rows with duplicating keys by the last seen row with that key. It means that new points will be added to the table, points with already existing keys in the table will be overridden.
So, all you need is to manage keys and apply points according to your mapping. For details, check the following sample, that simulates exactly what you need - https://playground.anychart.com/Cplq7KMd

Unable to write data (addRow) into Excel file in Nodejs

I'm trying to write data into an Excel file using ExcelJS library. I was successfully able to create worksheet and add column data.
However, while trying to implement addRow() or addRows() method, the data is not added into the Excel worksheet.
Here is the code I tried:
const ExcelJS = require('exceljs');
var workbook = new ExcelJS.Workbook();
var worksheet = workbook.addWorksheet('Payment Data');
worksheet.columns = reportHeaders; //reportHeaders is an array of header objects
I'm able to see the columns created successfully in the excel sheet. The trouble starts from below, where I'm trying to add data (into rows):
1st method :
worksheet.addRows(excelData);//excelData is an array of data objects
2nd method:
for(var rowItem in excelData){
worksheet.addRow(excelData[rowItem]);}
However, it seems either of these methods aren't working for me.
Finally, the file is saved:
workbook.xlsx.writeFile('PaymentData.xlsx')
Is there anything I'm missing? Any help will be appreciated.
So the issue with your code was, you were trying to add the data to the columns without specifying the key property in the columns array and hence it was unable to add the data.
I modified the worksheet.columns array to look something like the following:
worksheet.columns = [
{ header: "A", key: "a" },
{ header: "B", key: "b" },
];
This will solve your problem
I managed to convert the object to an array and passed it to the addRow method.
This worked for me.
I'm still not sure why I'm not able to pass an array of objects to addRow method.

Data not showing up in Google Chart

I've looked at every thread I could find on how to get a json feed into my google chart, but nothing seems to be working or the threads are slightly different from my problem.
Update: I'm trying to parse my json feed to only show certain columns. For example, my feed has a Actual and Goal column. I want my chart to only show the Actual column. I need the goal column for filtering reasons on the back end, so when the feed updates from the database it knows which records to pull.
After carefully following the json format for Google charts and figuring out a way to add the data, i'm am still unsuccessful in getting the actual data to show up. What's weird is that the graph shows up, it just doesn't have any data in it. I get no errors in my console.I've made sure my json string is valid, it is. I've tried logging my json feed to make sure that the information is being passed correctly and it is. The columns are added, as in the code, but the rows just won't show up.
I believe that in my data.addRow line, i'm not traversing correctly, but can't seem to figure out how to correctly get down to the specific cell.
function drawChart() {
$.ajax({
url: "--",
dataType:"json",
success: function (result) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Quarter');
data.addColumn('number', 'Actual');
for (var i = 0; i < result.rows.length; i++) {
data.addRow([result.rows[i], result.rows[i], result.rows[i]]);
}
Here is my json feed:
{ "cols":[ {"label":"Quarter", "type":"string"},{"label": "Actual", "type":"number"}, {"label":"Goal","type":"number"}], "rows":[ {"c":[{"v":"Q1"}, {"v":22}, {"v":30}]},
{"c":[{"v":"Q2"}, {"v":24}, {"v":30}]},
{"c":[{"v":"Q3"}, {"v":27}, {"v":30}]}
]}
You could build the DataTable with your raw JSON:
var data = new google.visualization.DataTable(json);
and then use a DataView to filter out your "Goal" column:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1]);
Draw your chart using the DataView instead of the DataTable:
chart.draw(view, options);
You can pass your response data from ajax call (as Json formated) to your DataTable
var data = new google.visualization.DataTable(responseData);

Highcharts Line Chart - Hyperlink on a data point

I am working on an application to create Line Chart using the Highcharts API. This application involves plotting a Date vs. Time Line Chart.
I need to have dynamic hyperlinks, for all or some of the data points.
The data for this chart is being retrieved from a database table and converted into JSON. This JSON is then being parsed by JavaScript and converted into data array that can be consumed by the Highcharts API. There is some data manipulation being done in the JavaScript while converting the data from JSON to data array.
The Highcharts API accepts the input in data array format that comprises of [x, y] combinations.
As I need to have a dynamic hyperlink for all or some of the data points, I have created another array that comprises of the hyperlinks.
I am unable to retrieve the hyperlink URL from the array on the fly as a particular hyperlink is clicked by the user.
I tried using it they was it has been used in this fiddle, http://jsfiddle.net/awasM/1/
A snippet of my code is given below:
series: [{
name: 'Release',
data: dataArray,
URLs: urlArray,
point: {
events: {
click: function() {
var someURL = this.series.userOptions.URLs[this.x];
if (someURL != "undefined")
window.open(someURL);
}
}
}
}]
However, as in my case date (in Unix/Epoch time format) is on x-axis (and time on y-axis), so using the x-axis value does not work.
i hope you could match this code to fix something.
point: {
events: {
click: function() {
var pointObject = this;
var pointindex = pointObject.x;
var pointdata = pointObject.y;
var getIndexOfURL = this.series.userOptions.URLs[pointindex];
var getIndexOfData = this.series.userOptions.data[pointindex];
if (getIndexOfURL){
window.open('http://'+getIndexOfURL);
}
}
}
}

Highcharts How to update all series with ajax

I have a function used to get data for my chart by ajax but I have a problem when I want to update it.
I would like to do something like that
chart.series = data;
but it's not working.
And with JSON.parse(data) I have an error but there is no problem with the JSON I think.
Example
[{ name : "<0.5s", marker:{enabled:false}, data : [[21231,1]]},{ name : "<20s", marker:{enabled:false}, data : [[21231,1]]}]
Any idea ?
To set the series data dynamically, you need to call setData:
chart.series[0].setData(seriesData, false);
This just sets the data in an existing series. You wouldn't set all the other series options every time.

Categories

Resources