Google line chart not working - javascript

the following code writes data to the screen and this needs to be plotted in a graph. The graph should be similar to the attachment So, when the array indicator is calculated (line 112), it contains 3 subarrays: one with a date, one with normalised prices and one with the mRS values. The array indicator is also calculated 3 times: one for AAL, one for ABF and one for ADM. So I need 3 graphs displayed, one for each symbol.
So essentially the multilinechart code needs to be integrated into the transpose code whereby 3 line charts are generated, namely after the calculation of the indicator array
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
var prices = [['Date', 'AAL', 'ABF', 'ADM'],
['2016-12-01', 1207.5, 2514.55, 1847.00],
['2016-11-01', 1123.5, 2475.00, 1901.00],
['2016-10-01', 1131, 2462.00, 1917.00],
['2016-09-01', 967.6, 2600.00, 2049.00],
['2016-08-01', 779.8, 3041, 2013.36],
['2016-07-01', 830.5, 2691, 2125.32],
['2016-06-01', 726.9, 2719, 1993.72],
['2016-05-02', 600.1, 2933.644, 1933.282],
['2016-04-01', 763.4, 3053.222, 1792.365],
['2016-03-01', 552.1, 3337.219, 1913.98],
['2016-02-01', 480.25, 3394.019, 1671.716],
['2016-01-04', 277.45, 3138.919, 1712.254],
['2015-12-01', 299.45, 3330.244, 1601.257],
['2015-11-02', 408.65, 3508.387, 1564.58],
['2015-10-01', 546.6, 3418.352, 1556.858],
['2015-09-01', 550.9, 3304.572, 1449.722],
['2015-08-03', 741, 3168.036, 1472.785],
['2015-07-01', 789.923, 3189.803, 1407.223],
['2015-06-01', 894.409, 2840.547, 1317.905],
['2015-05-01', 999.089, 2985.838, 1414.824],
['2015-04-01', 1076.017, 2817.219, 1458.897],
['2015-03-02', 985.457, 2778.762, 1432.678],
['2015-02-02', 1119.873, 3081.488, 1381.177],
['2015-01-01', 1030.099, 3059.794, 1355.894],
['2014-12-01', 1111.081, 3109.098, 1237.909],
['2014-11-03', 1223.068, 3134.425, 1161.125],
['2014-10-01', 1218.441, 2695.038, 1250.082],
['2014-09-01', 1280.913, 2621.644, 1201.39],
['2014-08-01', 1416.038, 2801.704, 1227.186],
['2014-07-01', 1461.646, 2718.524, 1339.334],
['2014-06-02', 1307.163, 2983.722, 1423.904],
['2014-05-01', 1332.301, 2943.89, 1340.253],
['2014-04-01', 1446.106, 2898.044, 1285.099],
['2014-03-03', 1395.374, 2712.71, 1290.464],
['2014-02-03', 1369.37, 2924.382, 1296.79],
['2014-01-01', 1284.4, 2648.331, 1305.827],
['2013-12-02', 1180.646, 2384.961, 1183.829],
['2013-11-01', 1206.584, 2212.07, 1123.282],
['2013-10-01', 1328.227, 2186.987, 1155.815],
['2013-09-02', 1357.743, 1809.787, 1114.245],
['2013-08-01', 1322.413, 1779.881, 1119.517],
['2013-07-01', 1242.815, 1875.387, 1245.585],
['2013-06-03', 1117.474, 1673.764, 1178.112],
['2013-05-01', 1347.412, 1738.319, 1187.878],
['2013-04-01', 1381.396, 1856.318, 1118.274],
['2013-03-01', 1493.496, 1823.7, 1162.796],
['2013-02-01', 1664.242, 1776.693, 1092.085],
['2013-01-01', 1633.503, 1677.881, 1067.642],
['2012-12-03', 1639.998, 1500.404, 1012.645]];
// Pairwise multiplication of the elements in two arrays; for use in mUp and mDown calculation
function dotproduct(a, b) {
var n = 0;
for (var i = 0; i < Math.min(a.length, b.length); i++) n += a[i][1] * b[i];
return n;
}
// Define array of weights that is global to the program
var weight = [];
// Weighting function
function weights() {
var k = 1;
var lambda = 2;
for (var x = 0.1; x < 20; x++) {
weight.push([x, k * Math.pow(x/lambda, k-1) * Math.exp(-Math.pow(x/lambda, k)) / lambda]);
}
}
// Create the weights
weights();
document.write(weight + '<hr>');
// Fetch first row of the prices array and keep the remainder as actual prices
var symbols = prices[0];
prices.shift();
// Loop through all columns of prices
for (var c in prices[0]) {
var min = prices[0][c];
var max = prices[0][c];
var up = [];
var down = [];
var indicator = [];
// Loop through all rows of prices and calculate the minimum and maximum, the up-value and down-value
for (var r in prices) {
min = Math.min(prices[r][c], min); // minimum price, for normalisation
max = Math.max(prices[r][c], max); // maximum price, for normalisation
var last = (typeof prices[parseInt(r)+1] != "undefined") ? prices[parseInt(r)+1][c] : 0;
up.push(Math.max(prices[r][c] - last, 0)); // up value
down.push(-Math.min(prices[r][c] - last, 0)); // down value
}
document.write('symbol: ' + symbols[c] + '<br>');
var mUp = []; // weighted up values
var mDown = []; // weighted down values
// Loop through all values of up and down and apply the weighting to the up and down values progressively
for (var i in up) {
mUp.push(dotproduct(weight, up));
up.shift(); // drop the first element off the up array
mDown.push(dotproduct(weight, down));
down.shift(); // drop the first element off the down array
}
// Add date and price to indicator array
for (var r in prices) {
indicator.push([prices[r][0], (prices[r][c]-min)/max, mUp[r]/(mUp[r]+mDown[r])]);
}
// *********
// Add the code to generate the line graph of array indicator here
// *********
document.write('indicator: ' + indicator + '<br>');
// Calculate percentile
document.write('first indicator: ' + indicator[0][2] + '<br>');
// Define a counter
var count = 0;
// Count the number of data points smaller than or equal to n
for (i in indicator) if (indicator[i][2] <= indicator[0][2]) count++;
document.write('count: ' + count + '<br>');
// Return the percentile
document.write('percentile: ' + count/indicator.length + '<br>');
document.write('<hr>');
}
</script>

Assuming that the array prices is the result of those calculations, you use .arrayToDataTable() to interface the data to the Google Visualization API.
SNIPPET
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>Line Chart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'AAL', 'ABF', 'ADM'],
['2016-12-01', 1207.5, 2514.55, 1847.00],
['2016-11-01', 1123.5, 2475.00, 1901.00],
['2016-10-01', 1131, 2462.00, 1917.00],
['2016-09-01', 967.6, 2600.00, 2049.00],
['2016-08-01', 779.8, 3041, 2013.36],
['2016-07-01', 830.5, 2691, 2125.32],
['2016-06-01', 726.9, 2719, 1993.72],
['2016-05-02', 600.1, 2933.644, 1933.282],
['2016-04-01', 763.4, 3053.222, 1792.365],
['2016-03-01', 552.1, 3337.219, 1913.98],
['2016-02-01', 480.25, 3394.019, 1671.716],
['2016-01-04', 277.45, 3138.919, 1712.254],
['2015-12-01', 299.45, 3330.244, 1601.257],
['2015-11-02', 408.65, 3508.387, 1564.58],
['2015-10-01', 546.6, 3418.352, 1556.858],
['2015-09-01', 550.9, 3304.572, 1449.722],
['2015-08-03', 741, 3168.036, 1472.785],
['2015-07-01', 789.923, 3189.803, 1407.223],
['2015-06-01', 894.409, 2840.547, 1317.905],
['2015-05-01', 999.089, 2985.838, 1414.824],
['2015-04-01', 1076.017, 2817.219, 1458.897],
['2015-03-02', 985.457, 2778.762, 1432.678],
['2015-02-02', 1119.873, 3081.488, 1381.177],
['2015-01-01', 1030.099, 3059.794, 1355.894],
['2014-12-01', 1111.081, 3109.098, 1237.909],
['2014-11-03', 1223.068, 3134.425, 1161.125],
['2014-10-01', 1218.441, 2695.038, 1250.082],
['2014-09-01', 1280.913, 2621.644, 1201.39],
['2014-08-01', 1416.038, 2801.704, 1227.186],
['2014-07-01', 1461.646, 2718.524, 1339.334],
['2014-06-02', 1307.163, 2983.722, 1423.904],
['2014-05-01', 1332.301, 2943.89, 1340.253],
['2014-04-01', 1446.106, 2898.044, 1285.099],
['2014-03-03', 1395.374, 2712.71, 1290.464],
['2014-02-03', 1369.37, 2924.382, 1296.79],
['2014-01-01', 1284.4, 2648.331, 1305.827],
['2013-12-02', 1180.646, 2384.961, 1183.829],
['2013-11-01', 1206.584, 2212.07, 1123.282],
['2013-10-01', 1328.227, 2186.987, 1155.815],
['2013-09-02', 1357.743, 1809.787, 1114.245],
['2013-08-01', 1322.413, 1779.881, 1119.517],
['2013-07-01', 1242.815, 1875.387, 1245.585],
['2013-06-03', 1117.474, 1673.764, 1178.112],
['2013-05-01', 1347.412, 1738.319, 1187.878],
['2013-04-01', 1381.396, 1856.318, 1118.274],
['2013-03-01', 1493.496, 1823.7, 1162.796],
['2013-02-01', 1664.242, 1776.693, 1092.085],
['2013-01-01', 1633.503, 1677.881, 1067.642],
['2012-12-03', 1639.998, 1500.404, 1012.645]
]);
var options = {
title: 'Line Chart',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>

Related

Getting a canvasjs graph to fit in a collapsed table row in Bootstrap?

I have created a canvasjs graph and want it to fit in a responsive table in Bootstrap.
I have created a large table in Bootstrap/HTML5 with one row defined as follows:
<tr>
<td colspan="100%" class="hiddenRow">
<div class="collapse" id="cellOneExp">
<div id="chartContainer1"></div>
</div>
</td>
</tr>
chartContainer1 refers to a dynamic graph created using canvasjs and has the following code:
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer1",{
zoomEnabled: true,
title :{
text: "Cell 1 Temperature (\xB0C)"
},
axisX: {
title:"Time (seconds)",
},
axisY:{
title: "Temperature (\xB0C)",
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 100;
var dataLength = 5000; // 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();
if (yVal>"100") {
$('#alertHigh').slideDown(); //callback function will go in the brackets to slide the alert back up
$('#alertLow').slideUp();
} else if (yVal<"-100") {
$('#alertLow').slideDown();
$('#alertHigh').slideUp();
} else {
$('#alertLow').slideUp();
$('#alertHigh').slideUp();
};
//print stuff
document.getElementById("cell1").innerHTML=yVal + "°C";
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval); }
The table has a button in it which has the id cellOneExp, so when that button is pressed the table should expand to show the graph.
If is replaced with anything else (for example a p tag) the table expands appropriately. However with the graph present the table does not expand correctly. Instead the graph overlays the rest of the table elements and I cannot figure out how to solve this. Thanks!

Google pie chart color depending on value

I have a chart where I only count the number of values for only two categories.
What I want is to color in green for that category having the max value and in blue for the one having the min value.
From the two quantity values, I want to determine inside the loop, the value that has the higher value. So the green color will be displayed for that value inside the pie chart, in this case, to be able to choose either 0 or 1 inside the options part, at the slices.
So far this is my code:
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(interinstituctionals_quantity);
function interinstituctionals_quantity(){/*Quantity de proyectos interinstitucionales del total de los proyectos vigentes*/
var data = new google.visualization.DataTable();
var interinstituctionals_quantity = {{interinstituctionals_quantity|json_encode|raw}};
var projectstotal = 0;
/****This is the array I get from the database:
['¿Interinstitutional?', 'Quantity'],
['yes', 70],
['no', 166],
****/
data.addColumn('string', '¿Interinstitucional?');
data.addColumn('number', 'Quantity');
$.each(interinstituctionals_quantity, function(index, value){
projectstotal += value.Quantity;/*Adding total of the quantity gotten from query*/
/*HOW can I determine inside this loop which of the two values has the highest value? And what if they're the same?*/
data.addRow([value.Interinstitucional,value.Quantity]);
});
var optionMax=1;
var optionMin=0;
var options = {
title: 'Number of interinstitutional projects (total: '+projectstotal+')',
backgroundColor: { fill:'transparent'},
height: 500,
is3D: true,
slices: {
0: { color: 'blue',offset: 0.5 },/*THIS TURNED OUT TO BE MAX AND SHOULD HAVE THESE OPTIONS*/
1: { color: 'green' }/*THIS TURNED OUT TO BE MIN AND SHOULD HAVE THESE OPTIONS*/
}
//width: 900,
};
var chart = new google.visualization.PieChart(document.getElementById('interinstituctionals_quantity_div'));
chart.draw(data, options);
function resizeHandler () {
chart.draw(data, options);
}
if (window.addEventListener) {
window.addEventListener('resize', resizeHandler, false);
}
else if (window.attachEvent) {
window.attachEvent('onresize', resizeHandler);
}
}
</script>
HOW can I determine inside this loop which of the two values has the highest value? And what if they're the same?
How do I achieve that?
something like this should work...
// assumes values will always exist and be positive
var maxAmount = -1;
var maxIndex = -1;
var areEqual = false;
$.each(interinstituctionals_quantity, function(index, value){
projectstotal += value.Quantity;/*Adding total of the quantity gotten from query*/
/*HOW can I determine inside this loop which of the two values has the highest value? And what if they're the same?*/
if (value.Quantity > maxAmount) {
maxAmount = value.Quantity;
maxIndex = index;
} else if (value.Quantity === maxAmount) {
areEqual = true;
}
data.addRow([value.Interinstitucional,value.Quantity]);
});

Use the HoverTool in BokehJS

I wrote some javascript to create a correlation plot in BokehJS (everything happens in the client, I can't use the Python Bokeh package).
Now, I would like to add a HoverTool to display tooltips when the user hovers over the squares, but I can't find documentation or examples on how to do this. I started looking at the coffeescript source and found relavant pieces, but I don't really understand how to integrate them.
Any help finding documentation or examples about how to use the HoverTool in pure BokehJS would be great.
This is a pure javascript version that works with Bokeh 0.12.4.
It shows how to use grid plot, with separate hovers over each set of data.
The {0.01} in the hover object is used to format the values to 2 decimal places.
var plt = Bokeh.Plotting;
var colors = [
'#ee82ee', '#523ebf', '#9bc500', '#ffb600', '#f50019', '#511150',
'#8b38fa', '#2e792a', '#ffef00', '#ff7400', '#a90064', '#000000'
]
function circlePlots(xyDict, plot_width, plot_height, title) {
// make the plot and add some tools
var tools = "pan,crosshair,wheel_zoom,box_zoom,reset";
var p = plt.figure({
title: title,
plot_width: plot_width,
plot_height: plot_height,
tools: tools
});
// call the circle glyph method to add some circle glyphs
var renderers = [];
for (var i = 0; i <= 3; i += 1) {
// create a data source
var thisDict = {
'x': xyDict['x'],
'y': xyDict['y'][i],
'color': xyDict['color'][i]
}
var source = new Bokeh.ColumnDataSource({
data: thisDict
});
var r = p.circle({
field: "x"
}, {
field: 'y'
}, {
source: source,
fill_color: colors[i],
fill_alpha: 0.6,
radius: 0.2 + 0.05 * i,
line_color: null
});
renderers.push(r);
}
var tooltip = ("<div>x: #x{0.01}</div>" +
"<div>y: #y{0.01}</div>" +
"<div>color: #color</div>");
var hover = new Bokeh.HoverTool({
renderers: renderers,
tooltips: tooltip
});
p.add_tools(hover);
return p
}
var pageWidth = 450;
var plotCols = 2;
var plots = [];
var plotWidth = Math.floor(pageWidth / plotCols)
if (plotWidth > 600) {
plotWidth = 600
}
var plotHeight = Math.floor(0.85 * plotWidth)
for (var i = 0; i < plotCols; i += 1) {
// set up some data
var M = 20;
var xyDict = {
y: [],
color: []
};
for (var j = 0; j <= 4; j += 1) {
xyDict['x'] = [];
xyDict['y'].push([]);
xyDict['color'].push([]);
for (var x = 0; x <= M; x += 0.5) {
xyDict['x'].push(x);
xyDict['y'][j].push(Math.sin(x) * (j + 1) * (i + 1));
xyDict['color'][j].push(colors[j]);
}
}
var title = "Sin(x) Plot " + (i + 1).toString();
var p = circlePlots(xyDict, plotWidth, plotHeight, title);
plots.push(p)
};
plt.show(plt.gridplot([plots], sizing_mode = "stretch_both"));
<link href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.css" rel="stylesheet" />
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.4.min.js"></script>
<script src="https://cdn.bokeh.org/bokeh/release/bokeh-api-0.12.4.min.js"></script>
First to use hover in bokeh you must add it as a tool and then personalise it to show what will be shown on hover. Look at this US Unemployment example from the bokeh docs
TOOLS = "hover,save"
p = figure(title="US Unemployment (1948 - 2013)",
x_range=years, y_range=list(reversed(months)),
x_axis_location="above", plot_width=900, plot_height=400,
toolbar_location="left", tools=TOOLS)
hover = p.select(dict(type=HoverTool))
hover.tooltips = OrderedDict([
('date', '#month #year'),
('rate', '#rate'),
])

NVD3 - How to refresh the data function to product new data on click

I have a line chart and every time the page refresh it changes the data, which is great but I need to to refresh by a user click. This is because there will eventually be other input fields on the page and refreshing the page would destroy their current session.
jsfiddle - http://jsfiddle.net/darcyvoutt/dXtv2/
Here is the code setup to create the line:
function economyData() {
// Rounds
var numRounds = 10;
// Stability of economy
var stable = 0.2;
var unstable = 0.6;
var stability = unstable;
// Type of economy
var boom = 0.02;
var flat = 0;
var poor = -0.02;
var economyTrend = boom;
// Range
var start = 1;
var max = start + stability;
var min = start - stability;
// Arrays
var baseLine = [];
var economy = [];
// Loop
for (var i = 0; i < numRounds + 1; i++) {
baseLine.push({x: i, y: 1});
if (i == 0) {
economyValue = 1;
} else {
var curve = Math.min(Math.max( start + ((Math.random() - 0.5) * stability), min), max);
economyValue = Math.round( ((1 + (economyTrend * i)) * curve) * 100) / 100;
}
economy.push({x: i, y: economyValue});
}
return [
{
key: 'Base Line',
values: baseLine
},
{
key: 'Economy',
values: economy
}
];
}
Here is what I tried to write but failed for updating:
function update() {
sel = svg.selectAll(".nv-line")
.datum(data);
sel
.exit()
.remove();
sel
.enter()
.append('path')
.attr('class','.nv-line');
sel
.transition().duration(1000);
};
d3.select("#update").on("click", data);
Here is what I did differently with your code.
// Maintian an instance of the chart
var chart;
// Maintain an Instance of the SVG selection with its data
var chartData;
nv.addGraph(function() {
chart = nv.models.lineChart().margin({
top : 5,
right : 10,
bottom : 38,
left : 10
}).color(["lightgrey", "rgba(242,94,34,0.58)"])
.useInteractiveGuideline(false)
.transitionDuration(350)
.showLegend(true).showYAxis(false)
.showXAxis(true).forceY([0.4, 1.6]);
chart.xAxis.tickFormat(d3.format('d')).axisLabel("Rounds");
chart.yAxis.tickFormat(d3.format('0.1f'));
var data = economyData();
// Assign the SVG selction
chartData = d3.select('#economyChart svg').datum(data);
chartData.transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
Here's how the update() function looks like:
function update() {
var data = economyData();
// Update the SVG with the new data and call chart
chartData.datum(data).transition().duration(500).call(chart);
nv.utils.windowResize(chart.update);
};
// Update the CHART
d3.select("#update").on("click", update);
Here is a link to a working version of your code.
Hope it helps.

JQuery FLOT chart dynamic Y-axis

I have a flot chart that calculates the max Y-axis value based on the last 100 data points and then plots successfully...
BUT
Sometimes, the running total of an ongoing plot (5 second delay with new data point plotted) exceeds the current max limit.
Is there a way to have the Y-axis scale dynamically while plotting new points on the chart?
This is a valid question about how to dynamically scale the Y Axis of the chart if the current Y-axis is exceeded, since the chart is plotted over time with new points being added every 5 seconds, I was asking how to scale the Y-Axis to fit the NEW plot data if it reaches above the current Max Y Axis value..
UPDATE:
here is the code I use (Json returned data) as well as the plot update timer:
The "highY" takes the last 100 datapoints from a database and sets the max value to the highest count + 10%
<script type="text/javascript">
$(function () {
var str1 = [], totalPoints = 300;
var str2 = [], totalPoints = 300;
var pts1 = '';
var pts2 = '';
if (pts1 == "" || pts == null) { pts = '2012-10-02 17:17:02'; }
if (pts2 == "" || pts == null) { pts = '2012-10-02 17:17:02'; }
var maxYaxis = <?PHP echo $highY; ?>;
function getStr1() {
var ts1 = new Date().getTime();
var json1 = (function () {
var json1 = null;
var myURL = '<?PHP echo $updateURL; ?>?s=1&ts=' + ts1;
$.ajax({
'async': false,
'global': false,
'url': myURL,
'dataType': "json",
'success': function (data) {
json1 = data;
}
});
return json1;
})();
var y1 = json1['data']['avgpersec'];
var total_1 = json1['data']['running_total'];
document.getElementById('<?PHP echo $string1; ?>Total').innerHTML = total_1;
if (str1.length > 0) { str1 = str1.slice(1); }
while (str1.length < totalPoints) {
var prev = str1.length > 0 ? str1[str1.length - 1] : 50;
str1.push(y1);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < str1.length; ++i){ res.push([i, str1[i]]) }
return res;
}
function getStr2() {
var ts2 = new Date().getTime();
var json2 = (function () {
var json2 = null;
var myURL = '<?PHP echo $updateURL; ?>?s=2&ts=' + ts2;
$.ajax({
'async': false,
'global': false,
'url': myURL,
'dataType': "json",
'success': function (data) {
json2 = data;
}
});
return json2;
})();
var y2 = json2['data']['avgpersec'];
var total_2 = json2['data']['running_total'];
document.getElementById('<?PHP echo $string2; ?>Total').innerHTML = total_2;
if (str2.length > 0) { str2 = str2.slice(1); }
while (str2.length < totalPoints) {
var prev = str2.length > 0 ? str2[str2.length - 1] : 50;
str2.push(y2);
}
// zip the generated y values with the x values
var res = [];
for (var i = 0; i < str2.length; ++i){ res.push([i, str2[i]]) }
return res;
}
// setup control widget
var updateInterval = 5000;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
if (updateInterval > 2000)
updateInterval = 2000;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: maxYaxis},
xaxis: { show: false },
colors: ["<?PHP echo $string1Color; ?>","<?PHP echo $string2Color; ?>"]
};
var plot = $.plot($("#placeholder"), [ getStr1(), getStr2() ], options);
function update() {
plot.setData([ getStr1(), getStr2() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
What i am hoping to accomplish is to adjust the "$highY" (Y-axis) value real time as i plot new data points so that the chart will scale if the value of the new data plot point exceeds the current "yaxis { max: # }" set in the chart options.
I'm assuming that right now you're using flot.setData and flot.draw?
The simplest solution is just to call $.plot with the new data each time you receive it. At various times, this has been recommended by the authors of the flot plugin as a reasonably efficient way of dealing with this situation. I've used this on graphs that refresh every second and found that it does not use an excessive amount of CPU on the user's computer, even with 3-4 graphs refreshing every second on one page.
EDIT based on the code you added (and your suggested edit), I would change the update function to look like this:
function update() {
var data = [ getStr1(), getStr2() ];
//modify options to set the y max to the new y max
options.yaxis.max = maxYaxis;
$.plot($("#placeholder"), data, options);
setTimeout(update, updateInterval);
}
Additionally, you would add code to getStr and getStr that keep the maxYaxis variable up to date.

Categories

Resources