Advanced charts in Wordpress
Introduction
I recently came across Highcharts, a great JavaScript library for creating charts. It uses canvas where it can, supports skins (easily changed with CSS). I’ve been searching/waiting for a decent JavaScript based charting API and it has finally arrived.
Seeing as I’m a wordpressaholic I’m of course going to try and get it into Wordpress. Although that might turn out to be quite more than I can chew.
Data Source
Highcharts can create charts from different sources; JSON, AJAX and HTML Tables. Each of which are actually scripted, but Highcharts has nice examples. For a Wordpress plug-in the most common source would be an existing HTML table. To be easily used as a source, it would require some structure. As an example I’ll take the Browser Statistics for 2009 from w3schools.com.
Table:
<table width="100%" cellspacing="0" id="chart-1-table"> <caption> <h2 class="title">Browser Statistics 2009</h2> <h3 class="subtitle">Source: <a href="http://www.w3schools.com/browsers/browsers_stats.asp" title="Browser Statistics at w3schools.com">w3schools.com</a></h3> </caption> <colgroup class="chart-axis-x"> <col width="16%" align="left" title="Month"/> </colgroup> <colgroup width="12%" align="center" class="chart-axis-y"> <col title="Internet Explorer 6"/> <col title="Internet Explorer 7"/> <col title="Internet Explorer 8"/> <col title="Firefox"/> <col title="Chrome"/> <col title="Safari"/> <col title="Opera"/> </colgroup> <thead> <tr> <th>2009</th> <th>IE6</th> <th>IE7</th> <th>IE8</th> <th>Firefox</th> <th>Chrome</th> <th>Safari</th> <th>Opera</th> </tr> </thead> <tbody> <tr> <th>November</th> <td>13.3%</td> <td>13.3%</td> <td>11.1%</td> <td>47.0%</td> <td>8.5%</td> <td>3.8%</td> <td>2.3%</td> </tr> <tr> <th>October</th> <td>12.8%</td> <td>14.1%</td> <td>10.6%</td> <td>47.5%</td> <td>8.0%</td> <td>3.8%</td> <td>2.3%</td> </tr> <tr> <th>September</th> <td>12.2%</td> <td>15.3%</td> <td>12.1%</td> <td>46.6%</td> <td>7.1%</td> <td>3.6%</td> <td>2.2%</td> </tr> <tr> <th>August</th> <td>10.6%</td> <td>15.1%</td> <td>13.6%</td> <td>47.4%</td> <td>7.0%</td> <td>3.3%</td> <td>2.1%</td> </tr> <tr> <th>July</th> <td>9.1%</td> <td>15.9%</td> <td>14.4%</td> <td>47.9%</td> <td>6.5%</td> <td>3.3%</td> <td>2.1%</td> </tr> <tr> <th>June</th> <td>7.1%</td> <td>18.7%</td> <td>14.9%</td> <td>47.3%</td> <td>6.0%</td> <td>3.1%</td> <td>2.1%</td> </tr> <tr> <th>May</th> <td>5.2%</td> <td>21.3%</td> <td>14.5%</td> <td>47.7%</td> <td>5.5%</td> <td>3.0%</td> <td>2.2%</td> </tr> <tr> <th>April</th> <td>3.5%</td> <td>23.2%</td> <td>15.4%</td> <td>47.1%</td> <td>4.9%</td> <td>3.0%</td> <td>2.2%</td> </tr> <tr> <th>March</th> <td>1.4%</td> <td>24.9%</td> <td>17.0%</td> <td>46.5%</td> <td>4.2%</td> <td>3.1%</td> <td>2.3%</td> </tr> <tr> <th>February</th> <td>0.8%</td> <td>25.4%</td> <td>17.4%</td> <td>46.4%</td> <td>4.0%</td> <td>3.0%</td> <td>2.2%</td> </tr> <tr> <th>January</th> <td>0.6%</td> <td>25.7%</td> <td>18.5%</td> <td>45.5%</td> <td>3.9%</td> <td>3.0%</td> <td>2.3%</td> </tr> </tbody> </table>
Style:
.chart table {
margin: 0;
padding: 0;
font-size: 0.86em;
}
.chart table tr {
line-height: 1.5em;
}
.chart table th,
.chart table td {
padding: 0.5em;
border-top: 1px solid #999999;
}
.chart table thead {
background-color: #F0F0F0;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#E0E0E0), to(#FFFFFF));
}
.chart table thead th {
border-bottom: 1px solid #999999;
border-top: 1px solid #999999;
}
.chart table thead th:first-child,
.chart table tbody th {
text-align: left;
}
.chart table tbody td {
text-align: center;
}
.chart table h2.title {
font-size: 1.2em;
margin-bottom: 0px;
}
.chart table h3.subtitle {
font-size: 0.86em;
margin-top: 0px;
}
Charting
The Highcharts API has a lot of options, too much to mention here, but a few are key to working successfully with pre-existing tables. The examples don’t use jQuery to parse the HTML, but since both Wordpress and Highcharts use it, I will too. These properties are static in the examples, but were they’ll need to be more dynamic; title, subtitle, xAxis, plotOptions.series. These options can be obtained from the table text or structure.
title and subtitle can be grabbed from the <caption>:
title: {
text: (function(){
var table = $('#chart-1-table');
var title = $('caption .title', table);
return title ? title.html() : '';
}())
},
subtitle: {
text: (function(){
var table = $('#chart-1-table');
var subtitle = $('caption .subtitle', table);
return subtitle ? subtitle.html() : '';
}())
},
Currently the title and subtitle are taken from tags with the ‘title’ and ’subtitle’ classes, but just using H2 and H3 (or H1 and H2) would work too of course.
xAxis as in the examples:
xAxis: {
categories: [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
],
title: {
text: 'Month'
}
}
Since we’ve got an existing table with labels, we can do it more dynamically.
xAxis from existing table:
xAxis: {
categories: (function(){
var table = $('#chart-1-table');
/*
* The first column in the table body uses <TH> tags,
* to separate them from data.
*/
var cats = $('tbody > tr > th', table)
.map(function(){
return $(this).text();
});
return $.makeArray(cats);
}()),
title: {
text: 'Month'
}
}
map allows you to turn the array with elements into an array with the actual text.
series as in the examples:
series: [{
name: 'November'
}, {
name: 'October'
}, {
name: 'September'
}, {
name: 'August'
}, {
name: 'July'
}, {
name: 'June'
}, {
name: 'May'
}, {
name: 'April'
}, {
name: 'March'
}, {
name: 'February'
}, {
name: 'January'
}]
Since we’ve got an existing table with labels, we can do it more dynamically.
series from existing table:
series: (function(){
var result = [];
var table = $('#chart-1-table');
/*
* Get all the columns from the table head.
* Some tables have multiple rows in the header.
*/
var head = $('thead > tr:last', table);
/*
* Skip the first column, it's the Y-axis label.
*/
var columns = $('th:gt(0)', head);
for (var i = 0, iMax = columns.length; i < iMax; i++) {
result.push(
{
name: $(columns[i]).text()
}
);
};
return result;
}())
And lastly the plotOptions.dataParser function:
dataParser: function(data) {
var result = [];
var table = $('#chart-1-table');
/*
* The series are defined by names, so we need to check what series we're in.
*/
var head = $('thead > tr:last', table);
var column = $('th:gt(0)', head).map(function(){
return $(this).text();
}).index(this.options.name);
/*
* Loop through all the data rows for this series.
*/
var rows = $('tbody > tr', table);
for (var i = 0, max = rows.length; i < max; i++) {
/*
* The first column (using a <TH> tag) contains the category name.
*/
var rowDate = $('th', rows[i]);
if (rowDate.size() > 1) {
rowDate = rowDate[0];
}
rowDate = rowDate.text();
/*
* Grab the cell in the right column for this series.
*/
var cell = $('td', rows[i])[column];
cell = $(cell);
/*
* Add an array to the result with the category name and cell value.
*/
result.push([
rowDate,
parseFloat(cell.text())
]);
}
return result;
}
The code for above dataParser is very specific for tables using categories. Tables with a lot more data that use timestamp should use xAxis.type = 'datetime' and convert the value of the row header to a UTC date.
Compete code:
var chart1 = null;
$(document).ready(function(){
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-1-container',
defaultSeriesType: 'line'
},
title: {
text: (function(){
var table = $('#chart-1-table');
var title = $('caption .title', table);
return title ? title.html() : '';
}())
},
subtitle: {
text: (function(){
var table = $('#chart-1-table');
var subtitle = $('caption .subtitle', table);
return subtitle ? subtitle.html() : '';
}())
},
xAxis: {
categories: (function(){
var table = $('#chart-1-table');
/*
* The first column in the table body uses <TH> tags,
* to separate them from data.
*/
var cats = $('tbody > tr > th', table)
.map(function(){
return $(this).text();
});
return $.makeArray(cats);
}()),
title: {
text: 'Month'
},
type: 'linear'
},
yAxis: {
title: {
text: 'Percent'
},
labels: {
formatter: function() {
return this.value + '%';
}
}
},
tooltip: {
formatter: function() {
return '<strong>' + this.series.name + '</strong><br />'+
this.x + ': ' + Highcharts.numberFormat(this.y, 1) + '%';
}
},
plotOptions: {
line: {
//stacking: 'percent',
lineColor: '#ffffff',
lineWidth: 1,
marker: {
lineWidth: 1,
lineColor: '#ffffff'
},
data: 'datatable',
dataParser: function(data) {
var result = [];
var table = $('#chart-1-table');
/*
* The series are defined by names, so we need to check what series we're in.
*/
var head = $('thead > tr:last', table);
var column = $('th:gt(0)', head).map(function(){
return $(this).text();
}).index(this.options.name);
/*
* Loop through all the data rows for this series.
*/
var rows = $('tbody > tr', table);
for (var i = 0, max = rows.length; i < max; i++) {
/*
* The first column (using a <TH> tag) contains the category name.
*/
var rowDate = $('th', rows[i]);
if (rowDate.size() > 1) {
rowDate = rowDate[0];
}
rowDate = rowDate.text();
/*
* Grab the cell in the right column for this series.
*/
var cell = $('td', rows[i])[column];
cell = $(cell);
/*
* Add an array to the result with the category name and cell value.
*/
result.push([
rowDate,
parseFloat(cell.text())
]);
}
return result;
}
}
},
series: (function(){
var result = [];
var table = $('#chart-1-table');
/*
* Get all the columns from the table head.
* Some tables have multiple rows in the header.
*/
var head = $('thead > tr:last', table);
/*
* Skip the first column, it's the Y-axis label.
*/
var columns = $('th:gt(0)', head);
for (var i = 0, iMax = columns.length; i < iMax; i++) {
result.push(
{
name: $(columns[i]).text()
}
);
};
return result;
}())
});
});
Demo
Next steps
The above code works great for a single instance, but for use in a plug-in it’s too scattered. The first thing to do is to create a dataSource Interface or base Class that provides functions for series, categories and dataParser.
For a Wordpress plug-in an advanced GUI for the WYSIWYG editor is needed to allow access to the complex options, not to mention a chart preview inside the editor.


