Created
March 24, 2011 04:06
-
-
Save hitode909/884560 to your computer and use it in GitHub Desktop.
plot table using jqplot http://www.dinkypage.com/108565
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jquery.plotHistogram | |
// requires jquery, jquery.jqplot, jqplot.barRenderer, jqplot.categoryAxisRenderer, jquery.jqplot.min.css | |
// call $.jqplot.config.enablePlugins = true; before use. | |
// usage: $('table.graph').plotHistogram(); | |
// usage: $('table.graph').plotHistogram({ target: $('#plot') }); | |
// this plugin can plot table like this. | |
// <table> | |
// <caption>the sample</caption> | |
// <tr data-key="0" data-value="10"><th>0</th><td>10</td></tr> | |
// <tr data-key="1" data-value="20"><th>1</th><td>20</td></tr> | |
// <tr data-key="4" data-value="10"><th>4</th><td>10</td></tr> | |
// </table> | |
// caption, data attributes are optional. | |
(function($){ | |
$.fn.plotHistogram = function(config){ | |
var defaults = { | |
target: null, | |
type: 'auto' // line, bar, else | |
}; | |
var options = $.extend(defaults, config); | |
var target = $(options.target); | |
if (target.length == 0) { | |
var target = $('<div>').css({ width: '500px', height: '300px' }); | |
$(this).after(target); | |
} | |
if (!target.attr('id')) { | |
target.attr('id', Math.floor(Math.random() * 100000000)); | |
} | |
var setLine = { | |
data: [], | |
ticks: [], | |
seriesDefaults: { }, | |
axes: { | |
xaxis: { ticks: [] }, | |
yaxis: { | |
min: 0, | |
tickOptions: { | |
formatString: "%d" | |
} | |
} | |
} | |
}; | |
var setBar = { | |
data: [], | |
ticks: [], | |
seriesDefaults: { | |
renderer: $.jqplot.BarRenderer | |
}, | |
axes: { | |
xaxis: { | |
ticks: [], | |
renderer: $.jqplot.CategoryAxisRenderer | |
}, | |
yaxis: { | |
min: 0, | |
tickOptions: { | |
formatString: "%d" | |
} | |
} | |
} | |
}; | |
var ticks = []; | |
var allNumber = true; | |
$(this).find('tr').each(function(index) { | |
var key = $(this).attr('data-key') || $(this).find('th').text(); | |
var value = $(this).attr('data-value') || $(this).find('td').text(); | |
if (allNumber && isNaN(+key)) allNumber = false; | |
var plotIndex = isNaN(+key) ? index : +key; | |
setLine.data.push([plotIndex, +value]); | |
setLine.axes.xaxis.ticks.push([plotIndex, key]); | |
setBar.data.push(+value); | |
setBar.axes.xaxis.ticks.push(key); | |
}); | |
var set = allNumber ? setLine : setBar; | |
if (options.type == "line") set = setLine; | |
if (options.type == "bar") set = setBar; | |
if ($(this).find('caption').length > 0) { | |
set.title = $(this).find('caption').text(); | |
} | |
$.jqplot(target.attr('id'), [set.data], set); | |
return this; | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment