Jump to content

4.0: Charts & Graphs

Charts and graphs are an essential tool in modern web applications. The API we use for displaying charts and graphs in IP.Board presently is something we wrote in-house during IP.Board 2.x - it uses the PHP GD library to generate an image representing a chart. At the time, it was pretty amazing, but as times have changed a number of libraries for generating much more visually appealing and interactive graphs have emerged. For IPS Social Suite 4.0 we've decided to retire our GD-based charting library and embrace something a bit more modern and familiar for developers to work with.

After looking at a number of different solutions, we decided to use Google Charts (although wrapped with a simple gateway PHP class). Google Charts look great, have great features, are commonly used (so we figure any third-party developers who want to add charts to their apps will be able to do so easily) and is a service provided for free with no API limitations.

I'll show you an example of how simple it is to create a chart in IPS Social Suite 4.0. Let's look at the code I might use to show a graph of the number of members registered over time:

		/* Init Chart */
		$chart = new IPSHelpersChart;
		/* Specify headers */
		$chart->addHeader( "Date", 'date' );
		$chart->addHeader( "Members", 'number' );
		/* Add Rows */
		$stmt = IPSDb::i()->build( array(
			'select'	=> "COUNT(*) AS count, DATE_FORMAT( FROM_UNIXTIME( joined ), '%Y-%m-%d' ) as joined_date",
			'from'		=> 'core_members',
			'group'		=> 'joined_date',
			'order'		=> 'joined DESC',
		) );
		while ( $row = $stmt->fetch() )
			$chart->addRow( array( new IPSDateTime( $row['joined_date'] ), $row['count'] ) );
		/* Output */
		IPSOutput::i()->output = $chart->render( 'LineChart', array(
			'title'	=> "Registrations",
		) );

As you can see, the code is extremely simple to understand and use. This is what the output looks like:

By hovering over any point I'll see a tooltip with the value at that point.

All of the chart types and options available in Google Charts are available to us. Let's make some changes to make the lines curved, get rid of the legend and show titles on each axis - I just change the last line of the code to:

		IPSOutput::i()->output = $chart->render( 'LineChart', array(
			'curveType' => 'function',
			'hAxis' => array(
				'title' => 'Date',
			'legend' => array(
				'position' => 'none',
			'title'	=> "Registrations",
			'vAxis' => array(
				'title' => 'Number of registrations',
		) );

And now my chart looks like this:

  • Create New...