Posts Tagged ‘graphs’

pChart – a PHP class to build charts

Posted in Code, Programming on September 11th, 2009 by Eric Lamb – 2 Comments

In my never ending quest to find a replacement for JpGraph  I’ve covered charts built using JavaScript with the Google Visualization API and charts done with SWFs using Open Flash Charts (OFS). If you’re building web apps it’s easy to just stop there and consider yourself covered. I certainly thought so; until my conscience spoke up that is.

pChart

pChart

The thought them comes creaping into my head, “Um… What about the JavaScript? How do you think those pretty charts and graphs will degrade?”.

Shit.

Not to take anything away from either of those programs; they’re very fun to work with and, relatively, easy to use. It’s just that they’re both rendered using JavaScript which is well and good provided your user has JavaScript enabled (and Flash too for OFS). It’d be a nice addition to provide an alternative when using either one of the previous programs.

This is where pChart comes in:

pChart is a PHP class oriented framework designed to create aliased charts. Most of todays chart libraries have a cost, our project is intended to be free. Data can be retrieved from SQL queries, CSV files, or manually provided. This project is still under development and new features or fix are made every week.

Focus has been put on rendering quality introducing an aliasing algorithm to draw eye candy graphics. Rendering speed has been dramatically enhanced since the first version, we’ll still continue optimising the code!

Implementation is pretty easy too:

// Standard inclusions
include("pChart/pData.class");
include("pChart/pChart.class");
 
// Dataset definition
$DataSet = new pData;
$DataSet->AddPoint(array(1,4,3,2,3,3,2,1,0,7,4,3,2,3,3,5,1,0,7));
$DataSet->AddSerie();
$DataSet->SetSerieName("Sample data","Serie1");
 
// Initialise the graph
$Test = new pChart(700,230);
$Test->setFontProperties("Fonts/tahoma.ttf",10);
$Test->setGraphArea(40,30,680,200);
$Test->drawGraphArea(252,252,252);
$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
$Test->drawGrid(4,TRUE,230,230,230,255);
 
// Draw the line graph
$Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
$Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);
 
// Finish the graph
$Test->setFontProperties("Fonts/tahoma.ttf",8);
$Test->drawLegend(45,35,$DataSet->GetDataDescription(),255,255,255);
$Test->setFontProperties("Fonts/tahoma.ttf",10);
$Test->drawTitle(60,22,"My pretty graph",50,50,50,585);
$Test->Render("Naked.png");
?>

The above code produces something similar to:

pChart Linechart Example

pChart Linechart Example

One really cool addition the developers added was a little cmd script, buildAll.cmd, to automate the build of all the Example scripts on Windows machines. Just double click that and you’ll have all the graph images generated automatically.

It is recommended by the developers that caching is implemented but I haven’t really found the need for it yet.

A good idea, and one I’m going to be implementing, is to use charts and graphs created with OFC and create static image graphs for the noscript tags using pChart. Definitely a lot of work but it’ll add a bit of shiny to my programs. Yours too I think.

Bookmark and Share

Prettify Data with Open Flash Chart

Posted in Code, Programming on June 10th, 2009 by Eric Lamb – Be the first to comment

Everyone likes the pretty. The pretty makes people feel nice and adds a sense of peace and comfort. The pretty is good and brings joy to small children.

Open Flash Charts

Open Flash Charts

We all want our data to be pretty. Tables of numbers just aren’t fun for anyone. Except programmers; we don’t give a shit.

Oddly though, PHP hasn’t had many options for pretty charts and graphs. Sure, we have JpGraph but it’s a little cumbersome and… well ugly’s a good word for it. Recently I heard about pChart, which I’ll be writing about another time, but aside from the cosmetic upgrade it doesn’t seem too different than JpGraph. 

I’ve already gone into some detail about the Google Visualization API, which is a pretty good JavaScript implementation for creating charts and graphs, but that too is a little challenging to implement.

I’ve recently become enthralled with Open Flash Charts (OFC) though. OFC is an open source flash charting system that uses external data-files to keep the program language agnostic. You can use pretty much any web programming language, so long as it can output strings, and you’re in business. In fact, there are libraries for a slew of languages including .NET, perl, python and ruby packaged right along with the download.

OFC was started because, I shit you not, the initial developer was burned by a vendor when looking for support on a PAID product. So he did what any programmer would do; wrote an open source version to help put that crappy company in hot water. Kudos :)

It’s a pretty slick setup though. OFC works by embedding a swf in a webpage and then setting a flashvar to point to a datafile on the server. Simple. Well… sort of…

There are 2 different versions to use; each given the very original titles v1 and v2 respectively. Near as I can tell the latest version uses JSON as the data format while version 1 uses something a little more… generic. The problem is that version 2 has only a couple examples and version 1 has a ton so while I like to use the latest and greatest I have to stick with version 1 for now. That’s what this article is going to focus on.

First, to get started, be sure to download the files from SourceForge. The download for version 1 was a little hard to find so, in the interest of helping others, I’m providing a direct link to download Open Flash Charts version 1.9.7. The download includes the swf, which you’ll obviously need to embed in your page, and the wrapper code which is provided in quite a few different lanuages (if you don’t do php).

Using the wrapper code makes creating the really complicated strings for the swf to absorb. Sure, you could do it by hand, but why the fuck would you?

The official site acutally has some really good examples of how to work with the code, so I won’t go into that too much here. Suffice it to say it’s pretty easy to create charts and graphs. The hardest part is getting used to the process of instantiating the code in the template (HTML) and then creating a stand alone script that gets hit by the swf for the data.

The HTML portion of the code is the simplest; you include the library (if it hasn’t been done already) and call a function like so:

1
2
3
4
<?php
include_once 'ofc-library/open_flash_chart_object.php';
open_flash_chart_object( $width, $height, $url, $use_swfobject=true, $base='' );
?>

The only two that should be confusing is $base and $url.

$base is useful if you don’t store the swf inside the site’s root directory; just set $base to the path, from your sites document root and you’re good.
For example:

2
3
4
5
6
7
8
<?php
//BAD
//$base = $_SERVER['DOCUMENT_ROOT'].'/path/to/open-flash-chart.swf';
 
//GOOD
$base = '/path/to/open-flash-chart.swf';
?>

$url is the full URL to the sister script to provide the options and data to the swf. It’s important to keep in mind that all the options for the swf are provided by this script. Seriously, all the options. What type of graph to generate, the data for the graph, the style for the graph, everything is generated on the server. The swf just interprets that data and draws accordingly.

The code for the sister script is a little more complicated but pretty straight forward once you understand it. NOTE, this was taken line for line from the official site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
// generate some random data:
srand((double)microtime()*1000000);
$max = 50;
$data = array();
for( $i=0; $i<12; $i++ )
{
  $data[] = rand(0,$max);
}
 
// use the chart class to build the chart:
include_once( 'ofc-library/open-flash-chart.php' );
$g = new graph();
 
// Spoon sales, March 2007
$g->title( 'Spoon sales '. date("Y"), '{font-size: 26px;}' );
 
$g->set_data( $data );
// label each point with its value
$g->set_x_labels( array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ) );
 
// set the Y max
$g->set_y_max( 60 );
// label every 20 (0,20,40,60)
$g->y_label_steps( 6 );
 
// display the data
echo $g->render();
?>

The above outputs a line chart like the below graph:

Example Graph

Example Graph

OFC is definitely worth a look for the pretty.

Bookmark and Share

Google Visualization API Primer

Posted in Code, Programming on March 30th, 2009 by Eric Lamb – Be the first to comment

The Google Visualization API is a JavaScript API for creating those fancy graphs and charts Google displays in all their cool toys like Google Analytics. There’s just an obnoxious amount of chart types available in the Visualization API Gallery that include code samples along with every example. There’s also the incredible Google Ajax API Playground which lets you play with the API and see real-time output.

Google Visualization

Google Visualization

According the official website:

The Google Visualization API lets you access multiple sources of structured data that you can display, choosing from a large selection of visualizations. Google Visualization API enables you to expose your own data, stored on any data-store that is connected to the web, as a Visualization compliant datasource. Thus you can create reports and dashboards as well as analyze and display your data through the wealth of available visualization applications. The Google Visualization API also provides a platform that can be used to create, share and reuse visualizations written by the developer community at large.

I have no real interest in publishing public widgets and I’ve only used the API by generating the data declarations; so far anyway. That’s actually what’s so compelling about the API; since it’s JavaScript based the API can be used with any server side language.

I’m mostly interested in using the charts and graphs for displaying data from a database on a website so that’s all this article is going to focus on.

One more thing to keep in mind; the API is just JavaScript. There’s nothing too fancy or random being done so even though the below may look complicated don’t forget; IT’S JUST JAVASCRIPT.

Examples

Line Chart

Line Chart

Line Chart

<script type="text/javascript">
	google.load("visualization", "1", {packages:["linechart"]});
	google.setOnLoadCallback(drawChart);
	function drawChart() {
		var data = new google.visualization.DataTable();
		data.addColumn('string', 'Date');
		data.addColumn('number', 'Clicks');
		data.addRows(15);
		data.setCell(0, 0, 'March 14, 2009');
		data.setCell(1, 0, 'March 15, 2009');
		data.setCell(2, 0, 'March 16, 2009');
		data.setCell(3, 0, 'March 17, 2009');
		data.setCell(4, 0, 'March 18, 2009');
		data.setCell(5, 0, 'March 19, 2009');
		data.setCell(6, 0, 'March 20, 2009');
		data.setCell(7, 0, 'March 21, 2009');
		data.setCell(8, 0, 'March 22, 2009');
		data.setCell(9, 0, 'March 23, 2009');
		data.setCell(10, 0, 'March 24, 2009');
		data.setCell(11, 0, 'March 25, 2009');
		data.setCell(12, 0, 'March 26, 2009');
		data.setCell(13, 0, 'March 27, 2009');
		data.setCell(14, 0, 'March 28, 2009');	  
                data.setCell(0, 1, 5);
		data.setCell(1, 1, 13);
		data.setCell(2, 1, 27);
		data.setCell(3, 1, 15);
		data.setCell(4, 1, 12);
		data.setCell(5, 1, 15);
		data.setCell(6, 1, 8);
		data.setCell(7, 1, 9);
		data.setCell(8, 1, 15);
		data.setCell(9, 1, 12);
		data.setCell(10, 1, 8);
		data.setCell(11, 1, 21);
		data.setCell(12, 1, 10);
		data.setCell(13, 1, 7);
		data.setCell(14, 1, 3);
 
		var chart = new google.visualization.LineChart(document.getElementById('click_chart_div'));
		chart.draw(data, {width: 500, height: 240, legend: 'bottom', title: 'Click Tracks by Date'});
	}
</script>
<div id='click_chart_div' style='width: 650px; height: 240px;'></div>

Pie Chart

Pie Chart

Pie Chart

<script type="text/javascript">
google.load("visualization", "1", {packages:["piechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
	var data = new google.visualization.DataTable();
	data.addColumn('string', 'Day');
	data.addColumn('number', 'Clicks');
	data.addRows(7);
	data.setValue(0, 0, 'Monday');
	data.setValue(0, 1, 56);
	data.setValue(1, 0, 'Tuesday');
	data.setValue(1, 1, 93);
	data.setValue(2, 0, 'Wednesday');
	data.setValue(2, 1, 21);
	data.setValue(3, 0, 'Thursday');
	data.setValue(3, 1, 28);
	data.setValue(4, 0, 'Friday');
	data.setValue(4, 1, 14);
	data.setValue(5, 0, 'Saturday');
	data.setValue(5, 1, 17);
	data.setValue(6, 0, 'Sunday');
	data.setValue(6, 1, 24);
 
	var chart = new google.visualization.PieChart(document.getElementById('day_chart_div'));
	chart.draw(data, {width: 500, height: 400, is3D: true, title: 'Clicks By Day', backgroundColor: '#f9f9f9', legend: 'top', legendBackgroundColor: '#f1f1f1'});
}
</script>
Bookmark and Share