How to get charts and reports in html5 dynamically? - javascript

I'm working on an android tablet application using phonegap in which i need to get a report chart which diagrammatically explains the status of different things, something like as shown in the picture below.
I want to generate these kind of charts or reports dynamically which varies as the data changes.Can anyone help me providing some examples using html5, js and css which has some similar functionality?

Did you check out RGraph: HTML5 & Javascript charts?
RGraph is a charts library written in Javascript that uses HTML5 to draw and supports over twenty different types of charts. Using the new HTML5 canvas tag, RGraph creates these charts inside the web browser using Javascript, meaning quicker pages and less web server load. This leads to smaller page sizes, lower costs and faster websites - everybody wins!
If you see a basic code, it goes this way:
<script>
window.onload = function ()
{
// The data to be shown on the Pie chart
var data = [564,155,499,611,322];
// Create the Pie chart. The arguments are the canvas ID and the data to be shown.
var pie = new RGraph.Pie('myPie', data);
// Configure the chart to look as you want.
pie.Set('chart.labels', ['Abc', 'Def', 'Ghi', 'Jkl', 'Mno']);
pie.Set('chart.linewidth', 5);
pie.Set('chart.stroke', 'white');
// Call the .Draw() chart to draw the Pie chart.
pie.Draw();
}
</script>
See a live example of Pie charts!
Yours is a Radar Chart. See one here: Radar Charts. Source code:
<script>
window.onload = function ()
{
// The data to be represented on the Radar chart.
var data = [3, 3, 41, 37, 16];
// Create the Radar chart. The arguments are the canvas ID and the data to be shown on the chart.
var radar = new RGraph.Radar('myRadar', data);
// If you want to show multiple data sets, then you give them like this:
// var radar = new RGraph.Radar('myRadar', [3,5,6,8], [4,5,2,6]);
// Configure the Radar chart to look as you wish.
radar.Set('chart.background.circles', true);
radar.Set('chart.color', 'rgba(255,0,0,0.5)');
radar.Set('chart.circle', 20);
radar.Set('chart.circle.fill', 'rgba(200,255,200,0.5)');
radar.Set('chart.labels', ['Safari (3%)', 'Other (3%)', 'MSIE 7 (41%)', 'MSIE 6 (37%)', 'Firefox (16%)']);
radar.Set('chart.key', ['Market share', 'A made up figure']);
// Now call the .Draw() method to draw the chart.
radar.Draw();
}
</script>

Check the below link.It really has some good examples.
http://www.highcharts.com/
Let me know if you still have any issues

A possible solution is to map CSS3 transitions to the graph. Here is a basic example demonstrating what you can do without using any javascript.
Here are some static examples produced with css (no javascript), I'm having a hard time finding interactive examples but as demonstrated in one of the previous links it is possible.

Related

Template level reactivity in Meteor

I'm working on a problem where I want to display data in a dashboard both as a chart (via perak:c3) and in a table (via aslagle:reactive-table). My issue is that the data is pulled from a collection in MongoDB, and it's format is instantly amenable to plotting via c3, but needs to be transformed into a local collection to be used by the reactive-table package, as suggested in this answer to a previous question.
When I change the dataset to be displayed I want the chart to be updated, and the table also. This requires changing the values in the local collection, however, which slows things down and so rather than the chart being smoothly redrawn, there is a freeze on the page, and then the new data is displayed.
I have created a sample project on GitHub here so the problem can be replicated easily. If you run the app and select a dataset in your browser you will see exactly what I mean
To see the reactive behaviour I want to preserve in the chart go to client/templates/dashboard/dashboard.html and simply comment out the table template {{> dashboardTable}}
and now change the dataset to see how the chart is smoothly redrawn. Essentially I am trying to ensure both templates dashboardChart and dashboardTable render independently of one another.
UPDATE
Following Michael Floyd's suggestion of using a timeout helped a bit
Meteor.setTimeout(function(){createLocalCollection(data)},200);
but although the chart gets smoothly drawn, when the table finishes being filled, the chart is drawn again. It looks like it jumps to some intermediate state that I can't understand. Here is a video showing what I mean.
I'm adding this as a separate answer because it's a completely different approach.
Use the onRendered callback in d3 to invoke the local collection update.
Where you have:
chart = c3.generate({
bindto: '#dataset-chart',
in dashboard_chart.js, add:
chart = c3.generate({
onrendered: createLocalCollection(),
bindto: '#dataset-chart',
Of course you need to remove createLocalCollection(data) from your event handler.
To avoid having to pass the data context through the onrendered handler in d3 also update your createLocalCollection function to use the reactive variable datasetID that you defined earlier to establish the current dataset:
var createLocalCollection = function() {
var values = My_First_Collection.find({datasetID: datasetID.get()}).fetch();
var tempDoc = {};
local.remove({});
tempDoc = {};
for (var i in values[0].value) {
tempDoc.value = values[0].value[i];
tempDoc.date = values[0].date[i];
local.insert(tempDoc);
}
};
Using this method you let D3 tell you when the chart rendering is done and then your table can start getting populated. The result is an instantaneous chart update followed by the table updating. No mucking with timeouts either.
Remember that js is single threaded. You have two things to and they are going to happen sequentially. What you can do is defer the code that is updating the local collection using Meteor.setTimeout(). This will allow the chart to update first and then your table can update second. I've seen this before where you run a function that updates the DOM (in your case d3 is updating the svg canvas) but the actual screen update gets stuck behind long running js.
I tried this specifically and chart performance was fine.
Meteor.setTimeout(function(){createLocalCollection(data)},500);
Cutting the interval down to 100 allowed the chart to update but then the menu didn't fade out completely until the local collection finished updating.
One thing that I've used with tables and local collections is to only update the local collection document when the corresponding non-local document is being rendered on screen (assuming there's a 1:1 relationship between the original data and the transformed version). This allows the reactive table to load lazily.

Highchart: addSeries vs. chart.options.series

I have inherited a project that is using Highcharts.
The previous dev used the .addSeries method to add all of the series to each chart that was being rendered. From what I've read of Highcharts, it seems like .addSeries is really for adding data dynamically.
The data that is being used to populate the charts are coming from an AJAX request. The old dev's approach was to get the data, render the chart, and then add a series using .addSeries. I was thinking that it might be better to update options.series and then pass the whole thing along to new Highcharts.Chart() for rendering, taking the .addSeries out of the equation.
However, since I'm new with Highcharts, I was hoping to get some feedback on what the better method would be.
You're on a good path, though your question suggests you may simply be looking for preference over a strict right/wrong answer.
From what I've seen, unless you have interactions on the page that would trigger a need to update your chart after it's been drawn, the benefit to using addSerie would be to add some visual flare. Using addSerie, your charts will visually draw themselves in front of the visitor - vs them already being drawn. (I believe HighCharts demo site has some good examples of this.)
I also recently inherited a HighCharts project and am generating a new Highcharts.Chart() using dynamic data by parsing the AJAXed data on the fly. The good news is that all of the charts still have nice visual flare (flare is important) since they don't draw until the AJAXed data is fully loaded. This snippet illustrates how I've been loading dynamic charts, parsing the JSON data on the fly:
$(function () {
var visitsChart;
$(document).ready( function() {
$.getJSON('/json-data-url', function(json){
var visitsChart = new Highcharts.Chart({
chart: {
renderTo: 'visitsContainer',
type: 'spline',
},
title: {
text: 'Test Widget'
},
series: [{
name: 'Speed',
data: [parseInt(json.visits)],
}],
...
});
});
});
});
I won't lie ... I had a few minutes of hair pulling when I got started but now I wish I had more time to work with Highcharts as it's quite fun once you get on a roll. Hope this helps.

heatmap-leaftet updating heatmap with more data

I am using the heatmap.js library from pa7 in github successfully to make some heatmap
http://www.patrick-wied.at/static/heatmapjs/example-heatmap-leaflet.html
But when I updated the heatmap with additional data or new data points, the leaflet library does not really update with the additional data points. There seems to be no method that can used for redraw. I dont know if someone has already solved this problem, thats why I am asking to see. Here is the simple portion of my additional script:
ndata=[{lat: 13.59, lon:-17.05, value: 11},{lat: 33.08, lon:-103.24, value: 19}]
testData.data.push.apply(ndata)
layer.addData(testData.data);
There is no errors in the console of Google chrome or no exceptions.
Thanks
There is a redraw method in the layer:
var heatmapLayer = L.TileLayer.heatMap();
// add layer to map
heatmapLayer.redraw()
Having said this, in the latest version, the heatmap layer automatically redraws when you set the data (see https://github.com/pa7/heatmap.js/blob/d09c4e99852b4849e2b4d4f12976a9fce0327ca5/src/heatmap-leaflet.js#L112).

Graphael documentation, recent samples, etc

I'm working on an implementation of a live-updating line graph using gRaphael which is a graphic extension of the Raphael SVG library.
I can't seem to find any examples of somebody doing this as a near-realtime updating project, which is fine. I'm assuming there's a way to call refresh on the graph with a new data set (without the need to re-initialize a whole new Raphael object each time!), but therein lies the problem:
There doesn't seem to be accurate documentation anywhere. I discovered this StackOverflow question: Graphael line chart which in turn led to this documentation project: https://github.com/kennyshen/g.raphael/tree/master/docs , but the results were cold. Using the examples provided, I ran into some errors:
the syntax r.g.linechart() used in the examples was no longer valid (where r is the Raphael object and I assume g is a gRaphael property within). Somewhere along the way somebody must have switched to properly extending the Raphael object so that r.linechart() worked.
The parameters passed into linechart() were incorrect, resulting in an undefined error again. If I passed in only the #x, #y, width, height, arrayX, arrayY parameters and dropped the chart labels, etc., I could render a plain line. But of course I need to be able to label my axes and provide a legend, etc.
Needless to say, a library without an API document isn't going to do anybody much good, but there are stalwarts out there who are willing to learn based strictly on reading the code itself. I'm not one of those. I would probably do OK with a well-commented example, preferably using live updates.
So I guess the questions are:
Does anybody know better documentation than the one I linked to?
Can someone point me to examples, documentation failing?
Can someone provide a proper itemization of the parameters that linechart() will accept?
Thanks!
For the record, here's how far I am so far:
var r = Raphael('line-chart');
// did NOT work -->
var linechart = r.g.linechart(
10,10,300,220,[1,2,3,4,5],[10,20,15,35,30],
{"colors":["#444"], "symbol":"s", axis:"0 0 1 1"}
);
// worked in a limited way, rendering a plain line with no visible labels/graph -->
var linechart = r.linechart(
10,10,300,220,[1,2,3,4,5],[10,20,15,35,30]
);
I am still trying to learn Raphael myself, but here are the primary resources I have been using: http://g.raphaeljs.com/reference.html and the same sans the "g."
here is a fiddle that pretty much pulls off an updating linechart with knockout/gRaphael, prob not the best solution, but its an idea: http://jsfiddle.net/kcar/mHG2q/
Just a note, I didn't start learning it until I combined reading with trial/error (with a lot of error), so play with the fiddle and see how things change.
but the basic code for it is like:
//constructor
var lines = r.linechart(10, 10, width, height, xVals, yVals, { nostroke: false, axis: "0 0 1 1", symbol: "circle", smooth: true })
.hoverColumn(function () { //this function sets the hover tag effect
this.tags = r.set();
for (var i = 0, ii = this.y.length; i < ii; i++) {
this.tags.push(r.tag(this.x, this.y[i], this.values[i], 160, 10).insertBefore(this).attr([{ fill: "#fff" }, { fill: this.symbols[i].attr("fill") }]));
}
}, function () {
this.tags && this.tags.remove();
});
lines.symbols.attr({ r: 3 }); //this adjusts size of the point symbols
There is a fork in GitHub that is working on the documentation and examples.
You will need to download the code and view it from you computer. It is a work in progress but it's more than you can find in the official g.Raphael page.
I also found this small post with some examples.

loading chart from data fetched using ajax call

I am using jqPlot javascript library ( http://www.jqplot.com/ ) for graphs and charts in one of my application.
In my application, there are 5-6 pages where this library is used. But I would like to discuss one particular case here.
On 1 of page, I am loading 3 charts. Data for these 3 charts is populated from database tables.
There is different set of queries for each chart. So, populated data for each chart is different too.
Once I have populated data, I have to process it, before providing its input to chart.
What is the problem then:
Problem that I am facing is it takes lots of time for page to render on browser (which is quiet obvious, as first it will form query, then fire that query against database tables, get the data, process on data and give to chart)
One of my friend suggested to implement following thing using ajax. I really liked his solution.
This is what I intend to do:
I would create a page, which will load all the required js/css files for jqPlot library.
There will be 3 sections on that page, where I would put some GIF images indicating that some process is going on (say ajax-loader.gif)
Once page is loaded, it will fire 3 ajax call, one at a time, to fetch each chart.
My Question Is how can I load chart from data received from ajax-call?
jqplot puts data and creates chart in following way (look at example below)
<script class="code" type="text/javascript">
$(document).ready(function(){
var plot2 = $.jqplot ('chart2', [[3,7,9,1,4,6,8,2,5]], {
// Give the plot a title.
title: 'Plot With Options',
// You can specify options for all axes on the plot at once with
// the axesDefaults object. Here, we're using a canvas renderer
// to draw the axis label which allows rotated text.
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer
},
// An axes object holds options for all axes.
// Allowable axes are xaxis, x2axis, yaxis, y2axis, y3axis, ...
// Up to 9 y axes are supported.
axes: {
// options for each axis are specified in seperate option objects.
xaxis: {
label: "X Axis",
// Turn off "padding". This will allow data point to lie on the
// edges of the grid. Default padding is 1.2 and will keep all
// points inside the bounds of the grid.
pad: 0
},
yaxis: {
label: "Y Axis"
}
}
});
});
</script>
Since you're using jQuery, you'd use the jQuery Ajax method to fetch the chart data after the page has loaded.
In your success function, your JS code (on the browser) receives the data from your server. Once you have the data, make the call to $.jqplot -- passing in the data you've just received.
To initially show the busy gif, just use the img element as the static content of the chart2 div which will later be the graph's container.
Some tips:
Some browsers don't do well at handling an animated gif while running a js program. So you may want to try a text message ("Loading chart...") in addition to the rotating gif. -- Or update the text messages. Eg start with "Fetching chart data from server" then update to "Processing chart data" once your success function has been called.
Rather than starting all 3 Ajax calls at once, experiment with having the success function for the first chart initiating the second Ajax call. (In addition to it charting the data.)
If you have problems with your Ajax calls, Google for examples and ask a separate question on SO if you still have problems.

Categories