Plotly update data - javascript

Okay so i have the following code:
var element = document.getElementById(scope.changeid);
function getData(division,redraw) {
var employeeData = [];
if (!division) {
$http.get(api.getUrl('competenceUserAverageByMyDivisions', null)).success(function (response) {
processData(response,redraw);
});
}
else {
$http.get(api.getUrl('competenceUserAverageByDivision', division)).success(function (response) {
processData(response,redraw);
})
}
}
function processData(data,redraw) {
var y = [],
x1 = [],
x2 = [];
data.forEach(function (item) {
y.push(item.user.profile.firstname);
x1.push(item.current_level);
x2.push(item.expected);
});
var charData = [{
x: x1,
y: y,
type: 'bar',
orientation: 'h',
name: 'Nuværende'
}, {
x: x2,
y: y,
type: 'bar',
orientation: 'h',
name: 'Forventet'
}],
layout = {
barmode: 'stack',
legend: {
traceorder: 'reversed',
orientation: 'h'
}
};
if(!redraw){
Plotly.plot(element, charData, layout);
}
else
{
Plotly.redraw(element,charData,layout);
}
}
scope.$watch('divisionId', function (newValue, oldValue) {
if (newValue) {
getData(newValue.id,true);
}
}, true);
getData(null,false);
Which creates the following chart:
Now as you can see ive added a watcher
scope.$watch('divisionId', function (newValue, oldValue) {
if (newValue) {
getData(newValue.id,true);
}
}, true);
Now when i trigger this it should update the chart and call Plotly.redraw(element,charData,layout);
However when it does this the chart does not change at all. There is no error in the console so i am not quite sure what to do?

Plotly.redraw(gd) is the right way.
But you call Plotly.redraw incorrectly.
The right way is update the data object, instead of new a data object.
var data = [{
x: ['VALUE 1'], // in reality I have more values...
y: [20],
type: 'bar'
}];
Plotly.newPlot('PlotlyTest', data);
function adjustValue1(value) {
data[0]['y'][0] = value;
Plotly.redraw('PlotlyTest');
}
Ref: http://www.mzan.com/article/35946484-most-performant-way-to-update-graph-with-new-data-with-plotly.shtml

I found the answer to the question.
Apprently i needed to use:
Plotly.newPlot(element,charData,layout);
instead of redraw

According to a Plotly community moderator (see the first answer here), Plotly.restyle is faster than Plotly.redraw and Plotly.newPlot.
Example taken from the link:
var data = [{
x: ['VALUE 1'], // in reality I have more values...
y: [20],
type: 'bar'
}];
Plotly.newPlot('PlotlyTest', data);
function adjustValue1(value)
{
Plotly.restyle('PlotlyTest', 'y', [[value]]);
}

The extendTraces function should be what you are aiming for. It can add data points to your graph and redraws it. In contrast to redraw (#Honghe.Wu Answer), you do not need to update the reference when using extendTraces.
[extendTraces] This function has comparable performance to Plotly.react and is faster than redrawing the whole plot with Plotly.newPlot.
https://plot.ly/javascript/plotlyjs-function-reference/#plotlyextendtraces
Example usage
// initialise some data beforehand
var y = [];
for (var i = 0; i < 20; i ++) {
y[i] = Math.random();
}
var trace = {
// x: x,
y: y,
type: 'bar',
};
var data = [trace];
// create the plotly graph
Plotly.newPlot('graph', data);
setInterval(function() {
// add data to the trace via function call
Plotly.extendTraces('graph', { y: [[getData()]] }, [0]);
// y.push(getData()); Plotly.redraw('graph'); //similar effect
}, 400);
function getData() {
return Math.random();
}

Related

plotly.js lag problem. my project is running slow

I have a project where I created the backend with flask. It reads the data from the csv file and transfers it to html. It reads data every second with Ajax. Then I visualize the data with plotly.js. With Ajax, every get operation comes with a delay.I am working with approximately 2000 data.
However, there is a delay in my code. How can I refactor this code? What can I do to avoid delay?
$(function requestData() {
$.ajax({
type: "GET",
url: "/deneme3",
success: function (data) {
//console.log('success',data);
//console.log('success',data[0]);
//console.log('success',data[1]);
var enlem = [];
var boylam = [];
var ch1 = [];
var ch2 = [];
var ch3 = [];
var ch4 = [];
enlem = data[0];
boylam = data[1];
ch1 = data[2];
ch2 = data[3];
ch3 = data[4];
ch4 = data[5];
//console.log('enlem',enlem);
//console.log('boylam',boylam);
var trace1 = {
x: enlem,
y: boylam,
mode: "markers",
marker: {
size: 10,
color: ch1,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
};
var data = [trace1];
var layout = {
title: "Scatter Plot with a Color Dimension",
};
Plotly.newPlot("tester", data, layout);
setInterval(function () {
var update = {
x: [[enlem]],
y: [[boylam]],
};
Plotly.extendTraces("tester", update, [0]);
}, 100);
//ch1 grafik
var trace2 = {
y: ch1,
type: "scatter",
};
var data2 = [trace2];
var layout2 = {
title: "CH1",
};
Plotly.newPlot("ch1", data2, layout2);
setInterval(function () {
var update = {
y: [[ch1]],
};
Plotly.extendTraces("ch1", update, [0]);
}, 100);
//ch2 grafik
var trace3 = {
y: ch2,
type: "scatter",
};
var data3 = [trace3];
var layout3 = {
title: "CH2",
};
Plotly.newPlot("ch2", data3, layout3);
setInterval(function () {
var update = {
y: [[ch2]],
};
Plotly.extendTraces("ch2", update, [0]);
}, 100);
//ch3 grafik
var trace4 = {
y: ch3,
type: "scatter",
};
var data4 = [trace4];
var layout4 = {
title: "CH3",
};
Plotly.newPlot("ch3", data4, layout4);
setInterval(function () {
var update = {
y: [[ch3]],
};
Plotly.extendTraces("ch3", update, [0]);
}, 100);
//ch4 grafik
var trace5 = {
y: ch4,
type: "scatter",
};
var data5 = [trace5];
var layout5 = {
title: "CH4",
};
Plotly.newPlot("ch4", data5, layout5);
setInterval(function () {
var update = {
y: [[ch4]],
};
Plotly.extendTraces("ch4", update, [0]);
}, 100);
},
});
setTimeout(requestData, 100);
});
Also, which of the Ajax and socketio would it make more sense to use?
As discussed in the comments, something like this might work: initialize empty plots, then just fill in data in the update function:
function plotData(data) {
const [enlem, boylam, ...chs] = data;
Plotly.extendTraces("tester", {
x: [[enlem]],
y: [[boylam]],
}, [0]);
for (let i = 0; i < 4; i++) {
const j = i + 1;
Plotly.extendTraces(`ch${j}`, {
y: [[chs[i]]],
}, [0]);
}
// After success, wait before loading more data
setTimeout(requestData, 1000);
}
function requestData() {
// Simulate a successful response that returns 6 numbers.
plotData([Math.random(), Math.random(), Math.random(), Math.random(), Math.random(), Math.random()]);
// If a real endpoint was available, you could do something like
/*$.ajax({
type: "GET",
url: "/deneme3",
success: plotData,
});*/
}
function initialize() {
Plotly.newPlot("tester", [{
x: [],
y: [],
mode: "markers",
marker: {
size: 10,
colorbar: { x: -0.2, len: 1 },
colorscale: "Jet",
},
}], {
title: "Scatter Plot with a Color Dimension",
});
for (let i = 1; i <= 4; i++) {
Plotly.newPlot(`ch${i}`, [{
y: [],
type: "scatter",
}], {
title: `CH${i}`,
});
}
requestData(); // Fire off first update
}
$(initialize);
div {
width: 33%;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js" charset="utf-8"></script>
<div id="tester"></div>
<div id="ch1"></div>
<div id="ch2"></div>
<div id="ch3"></div>
<div id="ch4"></div>

Bubble chart change X label values from a value in JSON response dynamically

I have a bubble chart using Chart.JS and getting my values dynamically from the database. The plotting of the data works absolutely fine, however I am trying to make a few formatting tweaks to the chart.
I want to change the X values to show the category (it is in my JSON output) on the horizontal axis rather than the i value. The JSON output contains category which is a string but I cant seem to do x: bubbleDatas[i].category?
The output currently shows on my x axis: 0,1,2,3,4,5 but i want it so show the value category from my JSON response which is in bubbleDatas?
data e.g.:
{
x: 0,
y: 60,
r: 10
}, {
x: 1,
y: 20,
r: 10
},
{
x: 2,
y: 40,
r: 10
}...
In my JSON response ajax request my X values i want it to be text:
e.g. 01_First, 02_Second
$(function () {
var bubbleData = [];
var xAxisLabels;
$.ajax({
type: "POST",
async: false,
url: "ExecView.aspx/ReturnData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var bubbleDatas = data.d;
bubbleData = new Array(bubbleDatas.length);
console.log(bubbleDatas);
for (i = 0; i < bubbleDatas.length; i++) {
if (bubbleDatas[i].score >= 60) {
rgbcolour = "#008000";
}
else if (bubbleDatas[i].score >= 50 && bubbleDatas[i].score < 60) {
rgbcolour = "#FFA500";
}
else {
rgbcolour = "#FF6347";
}
bubbleData[i] = { **x: i,** y: bubbleDatas[i].score, r: bubbleDatas[i].radius, backgroundcolor: rgbcolour };
console.log(bubbleData[i]);
}
}
});
var popData = {
datasets: [{
label: "Test",
data: bubbleData
}]
};
var bubbleOptions = {
responsive: true,
legend: {
display: false
},
tooltips: {
callbacks: {
label: function (t, d) {
return d.datasets[t.datasetIndex].label +
': (Category:' + t.xLabel + ', Score:' + t.yLabel + ')';
}
}
},
scales: {
yAxes: [{
ticks: {
// Include a % sign in the ticks
callback: function (value, index, values) {
return value + '%';
}
}
}]
}
};
var ctx5 = document.getElementById("bubble_chart").getContext("2d");
new Chart(ctx5, { type: 'bubble', data: popData, options: bubbleOptions });
});
Changing category to more meaning might be your specific requirement, check this fiddle if it helps bubble chartJS fiddle and check this labelling in chartJS
P.S. check out your condition for x-axis in the callback and print accordingly

Selecting Points over multiple Highcharts treemaps

Aim: I have two identical Highcharts treemaps and if I select one point of one chart, I also want to send a select event to the second chart's point with the same id/ same position.
Progress:
I followed these answers that tackle the same problem, only for line graphs, and then adopted the fiddle posted there for treemaps. You can find it here as well as below:
$(function () {
var prevPid = 0;
var chart = {
plotOptions: {
series: {
allowPointSelect: true,
point: {
'events': {
select: function () {
var pId = this.series.data.indexOf(this);
var chart1 = $('#container').highcharts();
var chart2 = $('#container2').highcharts();
chart1.series[0].data[pId].setState('select');
chart2.series[0].data[pId].setState('select');
chart2.series[0].data[prevPid].setState('');
prevPid = pId;
}
}
}
}
},
series: [{
type: "treemap",
data: [{
name: 'A',
value: 6,
colorValue: 1
}, {
name: 'B',
value: 6,
colorValue: 2
}, {
name: 'C',
value: 4,
colorValue: 3
}]
}]
};
$('#container').highcharts(chart);
$('#container2').highcharts(chart);
});
Problem: However the corresponding point of the other chart is not selected. Any advice on how to fix it?
Highcharts v5+
Instead of playing around with states, it's easier to use point.update(), demo: http://jsfiddle.net/BlackLabel/hy12z5u7/
Settings:
chart: {
events: {
load: function() {
$.each(this.series, function(i, s) {
$.each(s.data, function(j, p) {
p.pointAttr = {
select: {
color: "red"
}
};
});
});
}
}
},
And action:
point: {
'events': {
click: function() {
var pId = this.series.data.indexOf(this);
var chart1 = $('#container').highcharts();
var chart2 = $('#container2').highcharts();
chart1.series[0].data[prevPid].update({
color: chart1.series[0].color
});
chart2.series[0].data[prevPid].update({
color: chart2.series[0].color
});
chart1.series[0].data[pId].update({
color: chart1.series[0].data[pId].pointAttr.select.color
});
chart2.series[0].data[pId].update({
color: chart2.series[0].data[pId].pointAttr.select.color
});
prevPid = pId;
}
}
}
Highcharts < v4
The problem is that treemap doesn't have states.select option (API: http://api.highcharts.com/highcharts#plotOptions.treemap.states ) so even, when you force select-ed state, then nothing visually changes on your chart. You can add that state manually: http://jsfiddle.net/tqa6uxdb/3/
chart: {
events: {
load: function() {
$.each(this.series, function(i, s) {
$.each(s.data, function(j, p) {
p.pointAttr.select = {
fill: "red"
}
});
});
}
}
},
Note: your logic for selecting/deselecting points is missing checking if currently clicked point is already clicked.

How to create zoomable plot object using flot library in javascript?

Here is my code so far. I can see the selection rectangle, but zooming isn't happening.
what have I did wrong?
function Plot(container, data) {
this.options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
tickDecimals: 0,
tickSize: 1
},
selection: { mode: "xy" }
}
console.log("script is running")
this.data = []
this.container = container;
this.plot = $.plot(container, this.data, this.options);
this.url = '/sensor/oscillogram_debug_data/'+110;
this.container.bind("plotselected", this.zoom);
this.zoom = function(event, reanges) {
if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
ranges.xaxis.to = ranges.xaxis.from + 0.00001;
if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
ranges.yaxis.to = ranges.yaxis.from + 0.00001;
this.plot = $.plot(this.container, this.plot.getData(),
$.extend(true, {}, this.options, {
xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
}));
}
}
var plot = new Plot($("#output_plot_container"));
var updateChart = function() {
$.getJSON(plot.url, function(newdata) {
for (var f_id in newdata)
if (newdata.hasOwnProperty(f_id)) {
if (f_id='demodulated') {
// plot.plot.setData([newdata[f_id]])
// plot.plot.setupGrid()
// plot.plot.draw()
}
}
})
}
A few problems here:
1.) You are binding to this.zoom before it exists, reverse those calls (and note typo in "reanges"):
this.zoom = function(event, ranges) {
....
this.container.bind("plotselected", this.zoom);
2.) Your attempt at some sort of OO scoping within this.zoom just isn't going to work. Once that function is bound, it doesn't have access to it's parent scope. If you want the this to be available in the bind, you can pass it in as eventData:
this.container.bind("plotselected", {obj: this}, this.zoom); // and replace the this in this.zoom with obj
Here's a working fiddle.

Update Highchart data form exported button

I'm trying to use the exporting option to add a button which is then used to switch between a line chart with the real point and another with the cumulative sum of them.
I'm using the following code:
$(function () {
$('#container').highcharts({
chart: {
type: 'line'
},
xAxis: {
tickPixelInterval: 200,
categories: jsonResponse["Date"]
},
series: {
data: jsonResponse["values"]
},
exporting: {
buttons: {
'myButton': {
_id: 'myButton',
symbol: 'diamond',
text: 'Cumulative',
x: -62,
symbolFill: '#B5C9DF',
hoverSymbolFill: '#779ABF',
onclick: function() {
if(!cumulative){
this.series[0].setData = cumcum(jsonResponse["values"]);
alert(this.series[1].setData);
cumulative = true;
} else {
this.series[0].setData = jsonResponse["values"];
cumulative = false;
alert(this.series[1].setData);
}
},
_titleKey: "myButtonTitle"
}
}
}
});
});
function cumcum(data){
var res = new Array();
res[0] = data[0];
for(var i=1; i<data.length; i++) {
res[i] = res[i-1] + data[i];
}
return res;
}
From the alert I can see that the data are correctly calculated but the plot stays the same.
I also tried series[0].yData and series[0].processedYData
setData is a function, you have to call it like:
this.series[0].setData(cumcum(jsonResponse["values"])
See API http://api.highcharts.com/highstock#Series for more information.

Categories

Resources