Onclick redraw the chart with new values in bar chart - javascript

// 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.

Related

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.

Amcharts add value to dataset from external source (temperatue)

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>

How do I insert a node in a graph in sigmajs while inside angularjs

Note: I just vastly simplified the program and have left it with the bare essentials ...
So I am trying to add graphs within a sigma.js graph. First, let me post the javascript (sigmaAngualr.js) ...
app = angular.module('sigmaAngular', []);
app.controller('NetworkDataCtrl', function($scope){
var i, s;
$scope.newName = null;
$scope.s = null;
$scope.N = 3;
$scope.newNode = function (id, label){
return {id: id,
label: label,
x: Math.random(),
y: Math.random(),
size: Math.random()+0.2,
color:'#333'}
};
$scope.addNodeGraph = function(id, label){
$scope.s.graph.addNode($scope.newNode(id, label));
console.log(id+'-'+label);
};
$scope.tempNodes = [];
for( i=0; i<$scope.N; i++ )
$scope.tempNodes.push($scope.newNode('id'+i, 'Node'+i));
$scope.s = new sigma({graph:{nodes:$scope.tempNodes, edges:[]}})
});
app.directive('showGraph', function(){
// Create a link function
function linkFunction(scope, element, attrs){
scope.s.addRenderer({container: element[0]})
};
return {
scope: false,
link: linkFunction
}
});
And here is the HTML ...
<!DOCTYPE html>
<html>
<head>
<title>Using AngularJS</title>
<script type="text/javascript" src='lib/sigma/sigma.min.js'></script>
<script type="text/javascript" src='lib/angular/angular.min.js'></script>
<script type="text/javascript" src='lib/sigmaAngular.js'></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body ng-app='sigmaAngular'>
<div>
<div ng-controller='NetworkDataCtrl'>
<input type='text' ng-model='newName' />
<button ng-click='addNodeGraph(newName,newName)'> Add Node </button>
<hr>
<div show-graph id='graph-container' s='s' tempNodes='tempNodes'>
</div>
<hr>
</div>
</div>
</body>
</html>
Of course, I am unable to add a node to the graph.
I had also tried another option of creating an entire graph when I add a node. That doesnt work either. (This is no longer true)
Let me try to explain. Now,
When I refresh the browser, I do not see a graph.
When I resize the browser window The graph suddenly appears.
When I type a random name and hit the Add Node button, the graph doesnt change.
When I resize the browser window, the graph changes to reveal the new node.
So in summary, I have to resize the browser window to see any changes in the graph.
Just a side note: The css is below:
#graph-container {
position: relative;
width: 200px;
height: 200px;
border: 1px solid indianred;
}
I feel now that I am really close to solving the problem. Just a tiny bit off somewhere ...
Any help will be greatly appreciated!!!

how to focus the clicked bar in C3.js bar graph?

I have this code which makes a graph using c3.js : https://jsfiddle.net/1bxe2scd/
<!DOCTYPE html>
<html>
<head>
<title>Dsnap - Charts</title>
<!-- Load c3.css -->
<link href="c3/c3.css" rel="stylesheet" type="text/css">
<!-- Load d3.js and c3.js -->
<script src="d3/d3.min.js" charset="utf-8"></script>
<script src="c3/c3.min.js"></script>
</head>
<body>
<div id="chart" style="width:480px;height:400px"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var chart = c3.generate({
bar: {
width: 15
},
padding: {
left: 60
},
data: {
x: 'Date',
columns:
[
['Date', '2011-02','2013-01','2013-02','2013-03','2013-04','2013-05','2013-06','2013-07','2013-08','2013-09','2013-10','2013-11','2013-12','2014-01','2014-02'],
['value', 777,53,165,269,344,376,410,421,405,376,359,392,433,455,978]
],
type: 'bar',
onclick: function(e) { console.log(e.x);}
},
axis: {
rotated: true,
x: {
type: 'category'
}
},
tooltip: {
grouped: false
},
legend: {
show: false
}
});
</script>
</body>
</html>
I want the bar on which the user clicks to be focused and the rest of the bar should become faded, how can I achieve that?
How can I get the Y value of the clicked bar(eg: 2011-02 etc)?
You can do this for highlighting the bar:
onclick: function(e) {
//make all the bar opacity 0.1
d3.selectAll(".c3-shape").style("opacity",0.1);
var k = ".c3-shape-"+ e.index;
//make the clicked bar opacity 1
d3.selectAll(k).style("opacity",1)
}
Working code here
On clicking out side in the chart if you wish to bring back all the bars attach the click listener to the chart and on click make all bar's opacity 1:
d3.selectAll("#chart").on("click", function(d) {
//reset all the bars
d3.selectAll(".c3-shape").style("opacity", 1);
})
Working code here
EDIT
So now since you have two charts specify the id also to make it specific to the chart note the id in the selector: (#chart/#chart1):
d3.selectAll("#chart1").on("click", function(d) {
//reset all the bars for chart1
d3.selectAll("#chart1 .c3-shape").style("opacity", 1);
})
d3.selectAll("#chart").on("click", function(d) {
//reset all the bars for chart
d3.selectAll("#chart .c3-shape").style("opacity", 1);
})
On click for chart1 bar will look like this:
onclick: function(e) {
//make all the bar opacity 0.1 for chart1
d3.selectAll("#chart1 .c3-shape").style("opacity", 0.1);
var k = "#chart1 .c3-shape-" + e.index;
//make the clicked bar opacity 1
d3.selectAll(k).style("opacity", 1)
event.stopPropagation()
}
Working code here
Hope this helps!
C3 has callbacks, for specifying what should happen when a click (or mouseover/mouseout) event occurs:
http://c3js.org/reference.html#data-onclick
It also has "APIs": functions you can call to basically act like the user made a selection or focused:
http://c3js.org/reference.html#api-focus
You could hook one of these up to trigger the other, like have the onclick() function call focus().
But given what you're precisely looking for, the impediment would be that the focus() function doesn't accept the indices of individual bars on the graph. So it can only highlight an entire column/series of data at once, not individual bars. Here's the GitHub issue:
https://github.com/c3js/c3/issues/1389

Using Flot with multiple bars with orderbars.js and categories

I am having trouble creating multiple bars with flot. There is a plugin that can be downloaded here: http://www.benjaminbuffet.com/public/js/jquery.flot.orderBars.js that makes graphs with multiple bars per x category like this: http://www.pikemere.co.uk/blog/tutorial-flot-how-to-create-bar-charts/ (see under the customized bar charts). However, his example is a bit different in that it uses the time function rather than categories.
Here is my code:
<!doctype html>
<head>
<script language="javascript" type="text/javascript" src="/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="/flot/jquery.flot.js"> </script>
<script language="javascript" type="text/javascript" src="/flot/jquery.flot.categories.js"></script>
<script language="javascript" type="text/javascript" src="/flot/jquery.flot.orderBars.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var data1 = [
{
label: "Male" ,
data: [["True", 1],["False", 2]] ,
bars: {
show: true,
barWidth: 0.13,
order: 1
}
},
{
label: "Female" ,
data: [["True", 3],["False", 4]],
bars: {
show: true,
barWidth: 0.13,
order: 2
}
}
];
$.plot($("#placeholder"), data1, {
xaxis: {
mode: "categories"
},
});
});
</script>
<title>Test</title>
</head>
<body>
<div id="placeholder" style="width:600px;height:300px"></div>
</body>
</html>
With the above code, the graph displays, but without any bars. If I remove the order:1 and order:2, it displays correctly, except with the bars overlapping each other rather than being offset by each other (I think it just ignores the orderbars plugin).
This is a very simplified example of what I really want to do, but if someone knows how I can get it to do what I want fairly simply, I would be very much appreciative.
To sum up, what I want is to have two sets of two bars. The first set with "True" under them and the second second set with "False" under them. I do not want to use numbers to represent the values, if possible as it will greatly complicate my more complex situation. But if I must, I would still like to know how to do it that way.
change the function getAxeMinMaxValues in orderBars.js
function getAxeMinMaxValues(series, AxeIdx) {
var minMaxValues = new Array();
for (var i = 0; i < series.length; i++) {
series[i].data[series[i].data.length - 1][AxeIdx];
minMaxValues[0] = 0;
minMaxValues[1] = series[i].data.length - 1;
}
return minMaxValues;
}
hope this will help

Categories

Resources