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
Related
I am using depthchart from highcharts to show data that I am geting via websockets,I want to update the data without refreshing. I tried with setdata() and update() methods but the data is updated in a strange way
Strange data:
the desired result should look like
i am geting this when i initialize new depthchart
The problem with this was because I had dynamic (x,y) points and almost on every call the starting point was changing,i solved this by first updating the starting point
chart.series[0].update({
pointStart:updatedPoint,
})
and afterwards
chart.series[0].update({
data:newData,
})
I have an OData connection using which I read an entityset with conditions that returns me data in the following structure. The data being in the root node itself rather than in an object array-
oData Structure
I am then setting this data to a JSON Model and binding this model to my oTable.
The code in controller looks something like below-
//Get data for the table
var oTabData = sap.ui.getCore().byId("MyTable");
var sServiceUrl = "http://example.com/sap/opu/odata/SAP/ZXX_SRV";
var oModel2 = new sap.ui.model.odata.ODataModel(sServiceUrl,true);
var oJsonModel = new sap.ui.model.json.JSONModel();
oModel2.read("/MyEntitySet(Myvar1='000001',Myvar2='abc')?
$format=json",null,null,true,function(oData,response){
oJsonModel.setData(oData);
});
oTabData.setModel(oJsonModel);
The view contains the table and the binding is as below. Have ignored rest of table declaration code to keep it short. Table declared as oTable with id MyTable and with all the right columns-
//Template to map the data to the respective column
var template = new sap.m.ColumnListItem({
id:"table_template",
type: "Navigation",
visible: true,
cells:[
new sap.m.Label({
text: "{/Myvar1}"
}),
new sap.m.Label({
text: "{/Myvar2}"
}),
new sap.m.Label({
text: "{/Myvar3}"
}),
new sap.m.Label({
text: "{/Myvar4}"
})
]
});
var oFilters = null;
oTable.bindItems("/",template,null,oFilters);
The issues are-
As I have made a service call with conditions the oData output
received does not output an array of data like it does when we make
a call without conditions
(oModel2.read("/MyEntitySet?$format=json",null,null,true,function(oData,response)).
In the latter case the output comes under results array for which
the binding assignment is /results and that works right as expected.
In current case (service call with conditions), as the columns in
output are available right in the root level, have used binding /
and in template as well using / in front of every element (e.g.
{/Myvar1} as seen above). But using this technique it also creates 3
default blank lines in table initially. When the above controller
code is executed, it fills the table 3 x 4 times i.e. 12 rows for a
single row output.
Due to organization restrictions I cannot put the original code here. But this is how the scenario is. Any help would be appreciated.
Thanks.
PS: Haven't used any loop that would generate the repeated lines.
You can bind your table directly to the ODataModel:
Steps:
Before doing binding, you need to create a template for the table rows, in sap.m.Table it is ColumnListItem control, I would suggest to carry it out to the XML fragment. Try to use XML for markup as much as possible, becasue it much clearer and maintainablier than js coding;
All the controls in "cells" should be bound to the rows' properties using relative paths.
Tell the View about your model by calling "oView.setModel(MODEL_INSTANCE)", by this line you set the default model to the view. From now on all the controls inside are able to see it. The model is default because the name of it was not specified.
oTable.bindItems("/MyEntitySet", { template: oColumnListItem, filters: aFilters}); - this will automatically trigger an OData call to grab all needed data. The table will be updated automatically. You should see the rows.
In Google visualization ChartWrapper class, the code to draw a chart (bar chart, pie chart, etc) is as follows:
wrapper = new google.visualization.ChartWrapper({
dataTable: dataTable.toJSON(),
chartType: chartType,
options: options
});
console.log("Wrapper: " + wrapper.toJSON());
console.log(" ");
wrapper.draw(result[0]);
I am curious if there's an equivalent way of doing this using Highcharts where instead of calling new google.visualization.chartWrapper(...), we can just call something like new highcharts.chartWrapper(...). The options can include the container div id where the chart will be drawn.
Even if there is no way to do, any suggestions how I should be go about doing something similar to this?
As far as I know, in dataTable I can specify my data series in JSON format. In chartType, I can specify bar, column, pie, etc. Based on the highcharts example I saw, I can even write a service that generates a HTML file on the server side as shown here -> http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-basic/ and send back a response.
But what I don't know is how do I tell Highcharts to insert the chart right at container id specified in my options on the same page.
In this example, for instance, wrapper is just a json representation of the chart (which I can generate). What I am not sure is how do I convert that json representation to a highcharts map that gets inserted where I want on the same page.
Sorry, if this question seems complicated. I can clarify if you need additional information.
I'm trying to create a pie chart with javascript that will allow users to click on a slice and "view what makes up that slice." If you've ever used mint.com you'll know what I mean - say you're viewing an expenses pie chart and you click the "Automobile" slice, then you see the slice expand into a new chart of Gas, Maintenance, etc.
To take this a step further, I'm dealing with a large amount of data, so being able to fetch (ajax) the new data when the slice is clicked would be a useful option as well (though I can probably get away without it).
Perhaps "nested", "multi-level" and "drill-down" are not the right terms because I've been searching all day and cannot seem to find a solution.
Does anyone know of a library for this? Thanks in advance!
I've implemented similar drilldown systems using the HighCharts point click event. Here's the rough syntax:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie'
},
series: [{
data: myInitialDataArray, // make sure each data point has an id
point: {
events: {
click: function () {
$.post('/get/data/by/id/' + this.id, function(data) {
// you may need to format your data here
chart.series[0].setData(data);
});
}
}
}
}]
});
In this example, you define a click event that uses the point's id value (this.id) to perform an Ajax post to a URL. You then use the data from your post to re-bind the chart series.
Please note that each time you use the setData function to update the chart, each data point needs to have an id value in order for the drilldown to continue.
Hope this helps!
Try psd3 pie chart library
Demo - https://pshivale.github.io/psd3
Source - https://github.com/pshivale/psd3
It supports multi-level pie charts, donut charts and sunburst charts. It also supports drilling down a pie slice by double clicking it.
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);