Graph data from an HTML table using jQuery and flot

Posted

NOTE: A couple of commenters have pointed out that this plugin has issues in IE. I haven't had time to look into it, so I'm not sure whether they are related to my plugin or to flot. Make sure you read flot's readme about getting flot working in IE, I think it will address most IE issues. NOTE 2: I've posted a minor update to graphTable to remove an errant console.log call. NOTE 3: I've changed the license on the plugin; it is now dual-licensed MIT and GPL, like jQuery itself. I just got done with a first draft of the graphTable plugin, which lets you take a simple HTML table and turn the data in it into a graph using jQuery and flot. Here's a demo, and here's the jQuery plugin page where I'll continue development if there's any interest. The most basic usage is simple:

$('#table1').graphTable({series: 'columns'});
graphTable() takes up to two objects as arguments: the first is an object with the arguments for graphTable; the second is an object with arguments to be handed off to flot (read more about flot arguments). The graphTable arguments let you:
  • choose which parts of the table will be used for the graph data
  • choose where the graph will go in relation to the table and how big it will be
  • run a function on cell contents (to remove dollar signs, for example) before passing them to flot
Each of the following options can be set as part of an object passed to graphTable as the first argument. For example:
$('#table1').graphTable({
  series: 'columns',
  dataTransform: function(s) { return(s.replace('$','')); }
});

options for reading the table

defaults will work in most cases except you'll want to override the default args.series if your series are in columns
  • series 'rows', 'columns'
  • labels integer index of the cell in the series row/column that contains the label for the series; default is 0
  • xaxis integer index of the row/column (whatever args.series is) that contains the x values; default is 0
  • firstSeries index of the row/column containing the first series; default is 1
  • lastSeries index of the row/column containing the last series; will use the last cell in the row/col if not set; default is null
  • dataStart index of the first cell in the series containing data; default is 1
  • dataEnd index of the last cell in the series containing data; will use the last cell in the row/col if not set; default is null

graph size and position

  • position 'before', 'after', 'replace'; indicate whether the graph should go before the table, go after the table, or replace the table
  • width leave as null to use the width of the table for the width of the graph; otherwise, set to a width in pixels
  • height leave as null to use the height of the table for the height of the graph; otherwise, set to a height in pixels

data transformation before plotting

  • dataTransform function to run on cell contents before passing to flot; string -> string
  • labelTransform function to run on cell contents before passing to flot; string -> string
  • xaxisTransform function to run on cell contents before passing to flot; string -> string

Posted

57 comments

Dec 18, 2007
Michael said...
Just tried this plugin, and I love it, now I just need to decide where I want to use it. :)

Just one suggestion though, you might want to consider a setting for the margin of the graph, dependent upon position. When I place the graph below the table, the top edge of the graph is right on the bottom of the table. Although this could be resolved with CSS as well.

Anyway, great job.

Dec 19, 2007
Brandon Z said...
Very cool! How about getting it working with AFLAX, so that it uses Flash instead of <canvas>, so that it can be used by crappIE browsers. Or: it could check for canvas support, and use that when available... I suppose I should fire up my PC and see if its already doing that, but oh man I hate to use that thing when I don't absolutely have to.
Dec 19, 2007
rdmey said...
Michael: The div that the chart goes into has its own class (flot-graph), so I leave the styling to the whims of the user. Glad you like the plugin -- let me know if you use it somewhere!

Brandon: I hadn't given much thought to making this work with Flash instead of flot -- I think it wouldn't be hard, if there is a Flash chart library that could accept JSON data like flot can. That's really all this plugin does -- build an object that gets handed off to flot -- and it could just as easily hand that object off to something else. By the way -- you can use excanvas.js to get around the fact that IE doesn't support canvas. See the installation section of the flot README.

Dec 20, 2007
Skylog » Blog Archive » links for 2007-12-20 said...
[...] Graph data from an HTML table using jQuery and flot (tags: jquery) [...]
Dec 20, 2007
[jQuery]graphTable plugin « 轉折,然後向上 said...
[...] via:Graph data from an HTML table using jQuery and flot  Tagged with: jQuery [...]
Dec 21, 2007
ashish said...
Very cool. Recently i have been experimenting with google chart for displaying graphs. But this kind of plugins on top of jquery is much better and faster.
I hope, they make this part of jquery UI with lots of customizations.
Jan 21, 2008
Christian said...
That's a really great plugin!

I'm just wondering if I can use it for a time line with having the month (January, February,...) on the bottom line. Is that possible?

That would be a really great feature.

Thx

Jan 23, 2008
Steven said...
Rebacca, nothing seems to happen on the demosite? Just blank new div?
Feb 02, 2008
randy said...
can this be used with the flot functionality to turn dataset on and off in the graph?

thanks

Feb 04, 2008
nico said...
Hi ! Thanks for this great plugin. I'de like to add a little more functionnality by adding check boxes to choose which data will be displayed in the graph. Do you plan to enhance your plugin ? And if not, would you have a idea on how to make this happen ?
Thanks for your help.
Feb 13, 2008
rolfsf said...
wonderful. I haven't dug too deeply into the details, but is it easy enough to change from slope to block to point style graphs? In the case I'm thinking of, the user will select the type of graph, perhaps by select or radio button.
Feb 29, 2008
Jim said...
This is what I was looking for so I can provide plots on the iPhone with jQuery. It would be nice to allow alphanumeric axis labels. I am thinking of Dates in particular here. I am still figuring out how to use it, but I like what I have seen.
Mar 23, 2008
GorHal said...
Great article!! Mr nico, there is a sample with checkboxes. Check out http://code.google.com/p/flot/. Go to examples and select "Real data with a bit of interactivity". Here is an url to it: http://people.iola.dk/olau/flot/examples/real-data.html
Apr 09, 2008
Eric said...
i added a few things to the plugin that i thought were useful and i thought i would share:

i pass to flot the last x axis plot value as the "max" option to insure that the x axis extends out to the end of the data in the table (it seems to max out at 100 if no argument is passed).

i also created x and y axis ticks options to the plugin and pass those to flot to allow the ticks to be set manually.

Apr 18, 2008
KH said...
It would be nice if it was possible to choose other types of graphs than lines, f.x. bars.
May 13, 2008
Graham said...
Hi Rebecca,

I've got the plugin working nicely in stand alone pages, thanks!

When I put the page content into a jquery ui ajax tab (append new tab), the graph does not display fully. All I see is the legend and axes labels. Any ideas why that might be?

Jun 06, 2008
DJ said...
Your demos don't work in IE? Are they supposed to? Cool plugin, thanks for your work on it.
Jun 25, 2008
Robin said...
Hi Reb, nice plugin, thank you .. just, I think, your first sentence should be in bold: Not supported by IE (at least mine, v.7).
This would avoid a lot of later disappointment :)
Jul 18, 2008
rdmey | Fan mail said...
[...] Web Designing has pages about Ajax/JavaScript sample & Library. We like to introduce your graphTable. We make original samples with the graphTable. And then, we show how to use it with our samples. Is [...]
Jul 23, 2008
Tom said...
hey, i copied the source for your demo, correct the .js location in the script tags, and this does nothing. in ff or in ie. what am i doing wrong?
Sep 04, 2008
Duncan Pierce said...
Nice plugin - thank you. Could you give an example of using xaxisTransform? I've managed to use the other transforms without problems, but this one acts in a way I don't understand.
Sep 08, 2008
Duncan Pierce said...
There's a bug on xaxisTransform when using column series. To fix it, replace "y" with "x" near the end of this line:

if (args.xaxisTransform) { x = args.xaxisTransform(y); }

Oct 12, 2008
Random Syntax » Blog Archive » 6 jQuery Plugins to use within your content in a Learning Management System said...
[...] to any link with clueTip. 2. Help visualise tabular data, by transforming the data to graph with graphTable. 1. Embed all types of multimedia files with jQuery Media.     Read [...]
Oct 21, 2008
Peter G said...
Works fine IE 7 as long as you do the following:

1. Include excanvas in your html e.g:

(see flot doc for additional details)

2. Comment out the call to console.log in jquery.graphTable-0.1.js:

// console.log(tableData);

I did notice one problem (on IE and Firefox). I couldn't work out how to render bar graphs. The following code rendered a line graph with points:

$("#testGraph").graphTable({height: "250px"},
{xaxis : {tickDecimals: 0},
points: {show: true},
lines: {show: true}});

Downloads by Browser


Browser/Year
2006
2007
2008


FireFox
12
23
15


IE
37
43
23


Netscape
5
8
2

Changing this to

$("#testGraph").graphTable({height: "250px"},
{xaxis : {tickDecimals: 0},
bars: {show: true}});

Displayed a legend but no bars.

Oct 22, 2008
Rebecca said...
I've posted a minor update to the plugin to remove the errant console.log -- check out the link at the top of the post.
Jan 11, 2009
Charles said...
couple suggestions that i've included to fix an issue and expand the feature set:

for some unknown reason i had to declare local variable to test on becuase the inline !null was not working as expected.

// index of the row/column containing the last series
notdefined=!args.lastSeries;
if (notdefined) {

// index of the last cell in the series containing data
notdefined=!args.dataEnd;
if (notdefined) {

i added a plug-in option to specify a placeholder for the position instead of it being relative to the table which allows the graph to be anywhere on the page.

if (args.placement) {
$div = $("#"+args.placement);
} else
switch (args.position) {

i made the assumption that the x-axis will not be numeric and added the following:

rowData[rowData.length] = [i+0.5,y];
tickmarks[i-args.dataStart] = [i+0.5,y];

and

colData[colData.length] = [i+0.5,y];
tickmarks[i-args.dataStart] = [i+0.5,x];

and changed the flotArgs to be:

var flotArgs = { xaxis: { min: 1, max: tickmarks.length+1, ticks: tickmarks }, yaxis: { min: min, max: max } };

and the final change was to add a third configuration argument to allow for specifying the series properties. Like Peter G., i wanted to have one series to use bars.

$.fn.graphTable = function(graphArgs_,flotArgs_,seriesArgs_) {

for (j=0;j 0) ? seriesArgs_[j] : seriesArgs_;
$.extend(true,tableData[j], pointArgs);
}

$.plot($div, tableData, flotArgs);

so my call is:

$('#tabledata').graphTable({series: 'columns', placement: 'dataplot', width: '500px'},
{y2axis: { min: 0, max: 100 }},
[
{bars: { show: true, align: "center", barWidth: 0.5 }},
{lines: { show: true }, points: { show: true }, yaxis: 2}
]);

Jan 14, 2009
Eric J said...
I'm having trouble getting my graph to show up. I have a table where the header row contains "Month-Year" (Jan-2009). The first column contains the names of people I want to graph sales figures for. I guess it would be similar to the example at the top of the page, but change the first column to people's names. The graph shows up, but with no lines. If I change the header to have only digits, the graph shows up perfectly. I want the header to have Jan-2008 and the graph's x-axis ticks to show that as well. Here is my onclick function:

('#table1').graphTable({series: 'rows'},{legend:{container:$('#legend')}}); $(this).remove();

Hope someone can help me out, I tried playing with the flot parameters a little but couldn't figure it out. It seems like I'm missing a setting.

Jan 14, 2009
Jeroen said...
including the ExplorerCanvas library in your design fixes the compatibility issues with ie6.

it can be found here:
http://code.google.com/p/explorercanvas/

Jan 15, 2009
Eric J said...
I was using the version that came with flot. I downloaded the version you posted too and got the same results. I still get the graph but no lines. The labels across the bottom go from 0.1 -> 1.0. I was hoping for Jan-2008, Feb-2008 etc.
Jan 15, 2009
Eric J said...
I also took off the conditional wrapper around the canvas .js file to make sure it was getting included.
Mar 08, 2009
National Hack the Government Day said...
[...] JavaScript to generate a graph in the browser using the HTML table form of the data. Thanks to an article by Rebecca Murphey, we decided to use jQuery together with Rebecca’s graphTable jQuery plugin which uses the [...]
Mar 11, 2009
steve said...
Would you consider using style chart(free at chart.inetsoft.com) for this? It provides advanced charting for visualization.
Mar 18, 2009
jg said...
This was a great plug-in! I'm using v0.5 right now. My problem though is that when I use the mode: "time", the first month doesn't show up on the X-axis labels, how do I force it to show up?

Thanks.

May 22, 2009
Noel said...
Charles,
Thanks for your contribution. The seriesArgs_ extension was exactly what I needed. And being new to Javascript, your example was invaluable.

Here is my modified snippet:

$.fn.graphTable = function(graphArgs_,flotArgs_,seriesArgs_) {

.....

switch (args.series) {
......
}

if (seriesArgs_ != undefined) {
for (j=0;j<seriesArgs_.length;j++) {
$.extend(true,tableData[j], seriesArgs_[j]);
}
}

....

May 31, 2009
Ryan said...
Great plugin but the GPL license is a bit too restrictive. How about also giving it the MIT license like jQuery itself and most other jQuery plugins?
Jun 02, 2009
Rebecca said...
I've updated the plugin to be dual-licensed GPL and MIT, same as jQuery.
Jun 03, 2009
Noel said...
Here is another update I've made to for 'columns' type data tables.
This change allows columns to have blank entries ignored (previously, the script will set blank cells to 0). The following the is section under the case 'columns': portion (approx line 147)

...
case 'columns':
// iterate over each of the columns in the series
var $labelRow = $rows.eq(args.labels);

for (j=args.firstSeries;j<=args.lastSeries;j++) {
// j designates the column
var colData = new Array();

var label = $labelRow.find('th,td').eq(j).text();
if (args.labelTransform) { label = args.labelTransform(label); }

for (i=args.dataStart;i<=args.dataEnd;i++) { // i designates the row
$cell = $rows.eq(i).find('th,td').eq(j);

var y = $cell.text();
if (args.dataTransform) { y = args.dataTransform(y); }
test_y = parseFloat(y);

// test for a valid y value
if(!(isNaN(test_y))) {
if (test_y max) { max = test_y; }

var x = $rows.eq(i).find('th,td').eq(args.xaxis).text();
if (args.xaxisTransform) { x = args.xaxisTransform(x); }
test_x = parseFloat(x);

colData[colData.length] = [x,y];
}
}

tableData[tableData.length] = { label: label, data: colData };
}

break;
...

Thanks Rebecca!

Jun 26, 2009
Lukas said...
Charles,

i added your code, but now I get a firebug exception:

tickmarks is not defined
[Break on this error] tickmarks[i-args.dataStart] = [i+0.5,x];

I used your code

"$(’#tabledata’).graphTable({series: ‘columns’, placement: ‘dataplot’, width: ‘500px’},
{y2axis: { min: 0, max: 100 }},
[
{bars: { show: true, align: "center", barWidth: 0.5 }},
{lines: { show: true }, points: { show: true }, yaxis: 2}
]);"

so this should not be the error.

Can maybe someone post a link to a working js with this added features or does anyone have an idea what i did wrong?

Thanks

Jun 26, 2009
Lukas said...
Okey,

if i define var tickmarks = new Array();
i do not get an error, but nothing shows up anyway.

this is my js file:
http://veare.net/libs/js/jQuery.chart2.js

And this is trying to get ot to work:

$('#table').graphTable({series: 'columns', position: 'replace', dataTransform: function(s) { return(s.replace(' €','')); } , labels: 0, width: '860px', height: '500px'});

Jul 29, 2009
Duncan said...
Hi,

I seem to be having the issue that Noel, Charles and Peter had with the Bar Graph not showing up. I have made some changes in the code and even explicitly put:

174 tableData[tableData.length] = {label: label, data: colData};
175> $.extend(true,tableData[tableData.length-1],seriesArgs_);

which applies the seriesArgs_ to all series, then i used the following to call the function:

flotoptions={xaxis:{mode:'time'}};
flotseriesoptions={points:{show:true}, bars:{show: true, barWidth:24*60*60*1000}};

$("table").graphTable({},flotoptions, flotseriesoptions);

This does not seem to solve the problem, has anyone see what's wrong?

Jul 29, 2009
Duncan said...
After 2 days i finally figured it out!!!!

change:
171 colData[colData.length] = [x,y];
to
171 colData[colData.length] = [test_x,test_y];

Aug 22, 2009
Sammy said...
The Demo on Flot fails when using IE 8. The debugger shows line 152 as being the problem.

canvas = window.G_vmlCanvasManager.initElement(canvas);

An application that I developed works fine in IE 7 as well as IE 6.

Hopefully the author will look into this.

Sep 04, 2009
Reiwoldt said...
Hi, I am creating a table from a recordset so as to obtain dynamic data from a database, then using graphtable to graph the results. This works fine apart from the fact the xaxis that is made up of datetime values are not being parsed as date values. I have them written into the table using Javascript time formatting e.g. 1250944202000 but this is not then converted to a readable date.

Do I need to use a transformation arg? If so what would this look like?

Thanks

Sep 30, 2009
Eva said...
Hi, I got the same question as Reiwoldt ..
I got date data transform into epoch format but there are not parsed as date values , should I used xaxisTrasform or dataTransform .
I tried :
$('#table1').graphTable({series: 'columns', xaxis: { mode: "time" } });
but it didn't work .

Thanks eva

Oct 26, 2009
graphTable: graph data from HTML table using flot | jQuery Wisdom said...
[...] graphTable provides the ability to graph the data in a simple HTML table using flot. Web Site Demo Download AKPC_IDS += "965,";Popularity: 1% [?] Share and [...]
Nov 06, 2009
Phil said...
Hi, Rebecca.
Great plug in BTW.
In reply to Eva and Reiwoldt, I had the same problem with dates but have had success with the following.

$('#myTable').graphTable({series: 'columns', width:'50%', position:'replace',xaxisTransform:function(s){return(Date.parse(s));}},{xaxis:{mode:'time'}}); $(this).remove();

The xaxisTransform function gives the data to graphTable as epoch format (i.e milliseconds from 01/01/1970), from dates supplied from a database in the form of yyyy/mm/dd hh:mm:ss.
xaxis mode is a flot argument and needs to be separated from the graphTable args.

Eva if you haven't solved this try

$(’#table1′).graphTable({series: ‘columns’}, {xaxis: { mode: “time” } });

as I think your syntax is giving the xaxis mode as a graphTable argument.

Hope this helps, I'm little more than a hobbyist but have struggled with the same issues and now got mine working so I'm passing it on.

Nov 25, 2009
網站製作學習誌 » [Web] 連結分享 said...
[...] 用很簡單的方式就可以把表格資料轉換成圖表,用法可以參考這篇 Graph data from an HTML table using jQuery and flot [...]
Dec 19, 2009
25+ Highly Useful jQuery Plugins Bringing Life back to HTML Tables | tripwire magazine said...
[...] Graph data from an HTML table using jQuery and flot [...]
Dec 20, 2009
25+ Highly Useful jQuery Plugins Bringing Life back to HTML Tables | Afif Fattouh - Web Specialist said...
[...] Graph data from an HTML table using jQuery and flot [...]
Dec 21, 2009
Geech said...
For everyone that is having IE issues.

Make sure you have added the include that is in the flot read me file.)

Hopefully that should solve your IE problems.

Dec 25, 2009
Plugins jQuery para manejo de tablas HTML | Diseño web, accesibilidad, usabilidad, posicionamiento y optimización web - AlmacenPlantillasWeb Blog said...
[...] Gráficos de datos desde tablas HTML usando jQuery y flot [...]
Feb 20, 2010
Tom said...
For the life of me, I cant figure out how to get the dates to work. I basically took the example given in this blog and changed the x axis values to dates...I tried Unix time, m/d/y, y/m/d, and used what Phil said above but nothing works...please someone help me cause Im going crazy.
May 11, 2010
jQuery HTML 表格工具集 said...
[...] graphTable – 借助 flot 将 HTML 表格中的内容变成图形(演示)。 [...]
May 20, 2010
Sasidhar Kasturi said...
This ain't working with IE 8. I did include the excanvas.js.
Its failing at
line no: 153 in excanvas.js
el.innerHTML = '';
"el is undefined"
Jun 18, 2010
jQuery HTML Table Toolbox Plugins and tools | DX Articles said...
[...] graphTable The graphTable plugin lets you take a simple HTML table and turn the data in it into a graph using flot. [...]
Nov 16, 2010
styleworx said...
to the date problems:
For getting the date labels working use following code:
jQuery('#chart').graphTable({series: 'columns'}, {xaxis: {mode: "time"}

for the data source use sth. like this:
<th><?php echo strtotime($data->date.' UTC')*1000; ?></th>

It's important to format the date into timestamp and multiplicate with 1000 (for milliseconds). the dataformat in my example i got from a mysql db with the format like 2010/11/16.

hope that helps.

Jun 01, 2011
Julien said...
Hi,
Really nice work ! Great job !

Is there a way to choose the increment for the abscissa ?

Thanks

Leave a comment...