Amcharts add value to dataset from external source (temperatue) - javascript

I have a temperature sensor connected over http and I would like to add temperature to the Amcharts every 5 seconds. Have someone some example how to add new value to the current dataset? I will use line chart to represent temperature on y axis and datetime on x
thank you

The general idea behind dynamically updating a chart is to add a new element to your chart's dataProvider then call its validateData method. While it doesn't use AJAX, this demo basically has the framework laid out for you in the function that is called in the setInterval call:
setInterval( function() {
// make your ajax call here, then on a successful callback:
// add data item to the array
chart.dataProvider.push( {
/* new data */
} );
chart.validateData();
}, 5000 );
It also shifts the old data off the chart, which you may want to consider if you have a lot of data points added to the chart. A regular serial chart's performance will degrade after several hundred to a thousand points or so.

Ok.. I have done this example but it only shows me one value. Is this because the charData[] (array) contains only one value? (in the generateChartData function)
What I want is to draw a random value each second and push each time the graph to the left side..
here is example (copy/paste)
<!DOCTYPE html>
<html>
<head>
<title>chart created with amCharts | amCharts</title>
<meta name="description" content="chart created using amCharts live editor" />
<!-- amCharts javascript sources -->
<script type="text/javascript" src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="https://www.amcharts.com/lib/3/serial.js"></script>
<!-- amCharts javascript code -->
<script type="text/javascript">
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var chartData = generateChartData();
function generateChartData() {
var chartData = [];
var firstDate = new Date();
firstDate.setSeconds( firstDate.getDate());
chartData.push( {
date: firstDate,
temp: 0
} );
return chartData;
}
var timeout;
setInterval( function() {
chart.dataProvider.shift();
var newDate = new Date();
var temp = Math.round( Math.random() * 40 + 100 );
// dodamo podatek v graf
chart.dataProvider.push( {
date: newDate,
temp: temp
} );
if (timeout)
clearTimeout(timeout);
timeout = setTimeout(function () {
chart.validateData();
});
}, 1000 );
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": chartData,
"valueAxes": [ {
"position": "left",
"title": "Temperatura v °C"
} ],
"graphs": [ {
"valueField": "temp"
} ],
"categoryField": "date",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true
}
} );
</script>
</head>
<body>
<div id="chartdiv" style="width: 100%; height: 400px; background-color: #FFFFFF;" ></div>
</body>
</html>

Related

Drawing apexchart timeline chart with dynamic series of data

hi guys i am trying apexchart.js librry to draw a timeline chart.
i want a multiple series depending on tasks i have in sprint in bubble.io in which i want to give name and data parameter dynamically.
following is my code
<div id='chart' style='height: 70vh;'></div>
<script>
var task=[Parent group's Sprint's tasks:each item's Name:formatted as JSON-safe];
var names=[Parent group's Sprint's tasks:each item's developer:unique elements's Fname:formatted as JSON-safe];
var _startDates=[Parent group's Sprint's tasks:each item's Start-date:extract UNIX];
var _endDates=[Parent group's Sprint's tasks:each item's End-date:extract UNIX];
var startDates=[];
var endDates=[];
for(var i=0;i<task.length;i++){
startDates.push(new Date(_startDates[i]));
endDates.push(new Date(_endDates[i]));
}
console.log(names);
function getResult(){
var result=[];
var _data=[];
for (var j=0;j<task.lenght;j++){
_data.push({x:task[i],y:[startDates[i].getTime(), endDates[i].getTime()], fillColor: "#008FFB"})
}
for(var i=0;i<names.length;i++){
result.push({name:names[i],data: _data[i]});
}
return result;
}
var options = {
series:[
getResult()
],
chart: {
height: 450,
type: 'rangeBar'
},
plotOptions: {
bar: {
horizontal: true
}
}, xaxis: {
type: 'datetime'
}
};
var chart = new ApexCharts(document.querySelector("#chart"), options);
chart.render();
</script>
but it is giving me an error saying
It is a possibility that you may have not included 'data' property in series.
i would appreciate if anyone can suggest me where i am making mistake
thanks

morris.js line update ymin

Is there any way to update the ymin of a morris.js line/area?
I've tried it with:
chart.ymin = 10
but the ymin is still 0.
When it`s not possible in morris.js, are there any other chart libarys that include such a feature?
Solution 1
Make sure you set the Morris parameter resize to true.
Then, on your action, you can set the ymin, redraw the chart and make sure the chart is well positioned (trigger a window resize):
chart.ymin = 10;
chart.redraw();
$(window).trigger("resize");
Please try the following snippet:
var data = [
{ Date: '2016-01-01', Sales: 10 },
{ Date: '2016-01-02', Sales: 20 },
{ Date: '2016-01-03', Sales: 40 },
{ Date: '2016-01-04', Sales: 5 },
{ Date: '2016-01-05', Sales: 50 }
];
var chart = new Morris.Line({
element: 'chartLine',
data: data,
xkey: 'Date',
ykeys: ['Sales'],
labels: ['Sales'],
resize: true,
xLabels: 'day',
parseTime: false
});
$(".ymin").on("click", function() {
chart.ymin = 10;
chart.redraw();
$(window).trigger("resize");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css" rel="stylesheet" />
<div id="chartLine"></div>
<div class="ymin">Set ymin</div>
Solution 2
Set the Morris parameter resize to false for your temperature chart.
Make sure you include the Morris CSS available on the Morris GitHub. Without this CSS, hovering the chart will display the data at the bottom of the chart and will hide the x axis on the next data update from the setInterval.
Remove the code trying to get/set the chart height, triggering a window resize and calling the temperature chart redraw.
Finally add the following code in your $(document).ready function:
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function () {
delay(function () {
TemperatureChart.redraw();
}, 300);
}).trigger('resize');
Please try the following fork of your CodePen: codepen.io/krlzlx/pen/prwMLr

How to add toolbar to BokehJS plot?

My goal is to add a toolbar to a BokehJS plot. According to the plot tools documention this should be possible by doing (translating the Python example to Javascript):
plot.add_tools(new Bokeh.BoxZoomTool());
plot.add_tools(new Bokeh.ResetTool());
plot.toolbar_location = "right";
I have added these lines to the basic BokehJS example from the documentation, and they don't produce errors/warnings. However, the toolbar does not show up (properly) and the tools don't really seem to work.
I have prepared a minimal JSFiddle to demonstrate the problem: When using the rectangle select tool the plot moves around strangely, which uncovers an unstyled version of the toolbar rendered underneath the plot.
So the question is how can I get a properly working toolbar in BokehJS?
Add bk-root to the root element. <div id="plot" class="mybokehplot bk-root"></div>
Add corresponding css files (bokeh-0.12.0.min.css and bokeh-widgets-0.12.0.min.css).
JSFiddle here:
https://jsfiddle.net/blackmiaool/xzvgrqLj/
Snippet here:
// create some data and a ColumnDataSource
var x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);
var y = x.map(function(v) {
return v * 0.5 + 3.0;
});
var source = new Bokeh.ColumnDataSource({
data: {
x: x,
y: y
}
});
// create some ranges for the plot
var xdr = new Bokeh.Range1d({
start: -0.5,
end: 20.5
});
var ydr = Bokeh.Range1d(-0.5, 20.5);
// make the plot
var plot = new Bokeh.Plot({
title: "BokehJS Plot",
x_range: xdr,
y_range: ydr,
plot_width: 400,
plot_height: 400,
background_fill_color: "#F2F2F7"
});
// add axes to the plot
var xaxis = new Bokeh.LinearAxis({
axis_line_color: null
});
var yaxis = new Bokeh.LinearAxis({
axis_line_color: null
});
plot.add_layout(xaxis, "below");
plot.add_layout(yaxis, "left");
// add grids to the plot
var xgrid = new Bokeh.Grid({
ticker: xaxis.ticker,
dimension: 0
});
var ygrid = new Bokeh.Grid({
ticker: yaxis.ticker,
dimension: 1
});
plot.add_layout(xgrid);
plot.add_layout(ygrid);
// add a Line glyph
var line = new Bokeh.Line({
x: {
field: "x"
},
y: {
field: "y"
},
line_color: "#666699",
line_width: 2
});
plot.add_glyph(line, source);
// now add the tools
plot.add_tools(new Bokeh.BoxZoomTool());
plot.add_tools(new Bokeh.ResetTool());
plot.toolbar_location = "right";
// add the plot to a document and display it
var doc = new Bokeh.Document();
doc.add_root(plot);
var div = document.getElementById("plot");
Bokeh.embed.add_document_standalone(doc, div);
.mybokehplot {
position: relative;
width: 100%;
height: 100%;
border: 1px dashed #ccc;
}
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.0.min.js"></script>
<script type="text/javascript" src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.0.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.0.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.0.min.css">
<div id="plot" class="mybokehplot bk-root"></div>
P.S. I found that the edition of bokeh's css files and js files must be same, or you would get lots of bugs.

Onclick redraw the chart with new values in bar chart

// Dynamic Chart for bar Chart
$(function () {
(function(H) {
var each = H.each;
H.wrap(H.seriesTypes.column.prototype, 'drawPoints', function(proceed) {
var series = this;
if(series.data.length > 0 ){
var width = series.barW > series.options.maxPointWidth ? series.options.maxPointWidth : series.barW;
each(this.data, function(point) {
point.shapeArgs.x += (point.shapeArgs.width - width) / 2;
point.shapeArgs.width = width;
});
}
proceed.call(this);
})
})(Highcharts)
var getRandomData = function(size, addition) {
if (!addition) addition = 5;
var data = [];
var len = Math.random() * size + addition;
var i;
for (i = 0; i < len; i++) {
data.push(Math.random() * 50);
}
return data;
};
$('#bar-charts').highcharts({
chart: {
type: 'column'
},
series: [{
maxPointWidth: 50,
data: getRandomData(5)
}]
});
});
$('#reloadBar').click(function () {
// body...
$("#bar-charts").highcharts().reflow();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<div class="panel panel-shadow">
<div class="panel-body">
<div id="bar-charts"></div>
<a class="btn btn-success" id="reloadBar"><i class="glyphicon glyphicon-refresh"></i></a>
</div>
</div>
I was trying to redraw() the HighChart onclilck reload but was not getting any output, Don't know what mistake am doing. :?
Can some one help me how to get the random data onclick reload button
Heres the Updated Fiddle link:
https://jsfiddle.net/zeasts/tk3d3yen/
Thanks in Advance
Zeasts
To update Highchart's data manually, use Series.setData like this.
highchart's redraw, redraws chart with its current settings and data, to draw chart with new settings or data do the following steps:
define a method to the recreate chart:
var resetChart = function(){
$('#bar-charts').highcharts({
chart: {
type: 'column'
},
series: [{
maxPointWidth: 50,
data: getRandomData(5)
}]
});
};
Call the method to create the chart at beginning.
resetChart();
Define click handler like bellow and keep in mind that you should first destroy existing chart using highchart's destroy method and then call resetChart to draw new one:
$('#reloadBar').click(function () {
$("#bar-charts").highcharts().destroy();
resetChart();
});
Working Sample On Fiddle
Thanks to Wilts C, as he mentioned in his answer if you only want to change data you can also use series[index].setData method like this:
$("#bar-charts").highcharts().series[0].setData(getRandomData(5),true);
Working Sample On Fiddle With setData
hope that helps.

Pie chart using flot

I am using Jquery Flot to create a pie chart based on three different values, pause, nopause and sleeping. Initially it draws th pie chart correctly but after some redraw it gives me the following error.
Could not draw pie with labels contained inside canvas
My code is
Lecturer.socket.onmessage = function (message) {
var str = message.data;
var msg = str.split(":");
if(msg[0] == 'pause'){
var pause = parseInt(msg[1]);
var noPause = parseInt(msg[2]);
var sleeping = parseInt(msg[3]);
var data = [
{label: "Pause", data:pause},
{label: "No Pause", data:noPause},
{label: "Sleeping", data:sleeping}
];
var options = {
series: {
pie: {show: true}
},
legend: {
show: false
}
};
$.plot($("#pie-placeholder"), data, options);
}
};
HTML is
<div id="live-placeholder" class="flot"></div>
All the require js libraries are included. What I m doing wrong? Any Help ?
Thanks
You've got two problems:
1.) your placeholder div id doesn't match the $.plot call. live-placeholder != pie-placeholder.
2.) You don't need to calculate the percents yourself. Flot will do it internally.
See a working fiddle here.

Categories

Resources