Path

ez components / documentation / api reference / trunk / graph


eZ Components trunk

Graph

[ Tutorial ] [ Gallery ] [ Class tree ] [ Element index ] [ ChangeLog ] [ Credits ]

Introduction

The Graph component enables you to create line, pie and bar charts. The output driver mechanism allows you to create different image types from each chart, and the available renderers make the chart output customizable from simple two-dimensional charts to beautiful three-dimensional data projections.

ezcGraph separates different parts of the graph into chart elements, each representing one part of a graph. Elements include the title, the legend or an axis, and are all independently configurable. This design not only allows you to use different colors or fonts for each chart element, but also to define their position and size. The main chart elements are the same for all chart types. To define overall layouts for graphs, you can use palettes, which specify default colors, symbols, fonts and spacings.

Data is provided through ezcGraphDataSet objects, which are normally created from simple arrays. You also can perform statistical operations on data, as you will see later.

Class overview

This section gives you an overview of the most important classes.

ezcGraphChart
Line, bar and pie charts extend this abstract class, which represents the chart to be rendered. ezcGraphChart collects the data and chart elements, gives you access to all configuration settings and calls the driver and renderer for creating the final output.
ezcGraphDataSet
All datasets extend this abstract class to provide the data in a general form accessible by the chart.
ezcGraphChartElement
All chart elements store configuration values that define their layout. An element's layout definition contains background, border, margin, padding and font configuration. ezcGraphChartElement is extended by other classes for the legend, text, background and different axis types.
ezcGraphChartElementAxis
This class extends ezcGraphChartElement and is the base class for all axes. There are different axis types for different data to be displayed, such as numeric axis, string labeled axis or date axis.
ezcGraphAxisLabelRenderer
This class defines the rendering algorithm for labels and grids on an axis. The distinction between algorithms is necessary, because bar charts have labels placed directly below the data point, but numerical data in line charts should be placed next to the grid.
ezcGraphPalette
ezcGraphPalette contains color, font, symbol and spacing definitions to be applied to the entire graph.
ezcGraphRenderer
This renderer transforms chart primitives, like pie chart segments, legend or data lines, to image primitives. You have the choice between a two- and three-dimensional renderer.
ezcGraphDriver
This driver renders image primitives to an image. The default driver will output as SVG, but you can also render JPEGs or PNGs using ext/gd.

Chart types

Pie charts

The following is a simple example of how to create a pie chart using the default driver, palette and renderer.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphPieChart();
  4. $graph->title = 'Access statistics';
  5. $graph->data['Access statistics'] = new ezcGraphArrayDataSet( array(
  6. 'Mozilla' => 19113,
  7. 'Explorer' => 10917,
  8. 'Opera' => 1464,
  9. 'Safari' => 652,
  10. 'Konqueror' => 474,
  11. ) );
  12. $graph->data['Access statistics']->highlight['Opera'] = true;
  13. $graph->render( 400, 150, 'tutorial_simple_pie.svg' );
  14. ?>

Simply create a new chart object, optionally set a title for the chart, assign the data and render it. To assign data, the dataset container is accessed like an array to define an identifier for the dataset. The dataset in this example is created from an array, where the keys are used as the identifiers for the data points.

Pie charts accept only one dataset, and the data point identifiers are used to create the legend. To generate the output, the default SVG renderer is used with the default 2D renderer. By default, the colors are applied from the Tango palette, from the Tango Desktop Project: http://tango.freedesktop.org/Tango_Desktop_Project

Several dataset and data point presentation styles will be mentioned in this tutorial. One possibility is to highlight a special dataset or point. In line 15, the data point Opera is highlighted; in the case of pie charts, this segment is pulled away from the center. See the renderer options class ezcGraphRendererOptions for more details.

Sample pie chart

Pie chart options

There are several pie chart specific configuration options available. In eZ Components, options are always accessed via public properties. For a full list of all available options, see the documentation for the ezcGraphPieChartOptions class.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphPieChart();
  4. $graph->title = 'Elections 2005 Germany';
  5. $graph->data['2005'] = new ezcGraphArrayDataSet( array(
  6. 'CDU' => 35.2,
  7. 'SPD' => 34.2,
  8. 'FDP' => 9.8,
  9. 'Die Gruenen' => 8.1,
  10. 'PDS' => 8.7,
  11. 'NDP' => 1.6,
  12. 'REP' => 0.6,
  13. ) );
  14. $graph->options->label = '%3$.1f%%';
  15. $graph->options->sum = 100;
  16. $graph->options->percentThreshold = 0.02;
  17. $graph->options->summarizeCaption = 'Others';
  18. $graph->render( 400, 150, 'tutorial_pie_options.svg' );
  19. ?>

In line 16, a sprintf format string is set, which defines how the labels are formatted. Instead of a sprintf format string, you could also set a callback function to do label formatting.

In this example, we set a custom sum to force the pie chart to show the complete 100%. The percentThreshold lets the chart collect all data points that have less than the specified percentage to be aggregated in one data point. We also could define an absolute threshold, so that all data below a certain value would be aggregated in one data point. summarizeCaption defines the caption for this aggregated dataset.

Pie chart configuration options

Line charts

Line charts are created in the same way as pie charts, but they accept more than one dataset. We are using the default driver, palette and renderer in this example.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphLineChart();
  5. $graph->title = 'Wikipedia articles';
  6. // Add data
  7. foreach ( $wikidata as $language => $data )
  8. {
  9. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  10. }
  11. $graph->render( 400, 150, 'tutorial_line_chart.svg' );
  12. ?>

There are only two differences compared to the last example. In line 6, we instantiate a ezcGraphLineChart object instead of ezcGraphPieChart and beginning in line 10, we assign multiple datasets from an array we included earlier in the script. The array in the file tutorial_wikipedia_data.php is built like this:

  1. <?php
  2. return array(
  3. 'English' => array(
  4. 'Jan 2006' => 965,
  5. 'Feb 2006' => 1000,
  6. ...
  7. ),
  8. ...
  9. );
  10. ?>

The result is a simple, default line chart.

Simple line chart

Bar charts

Bar charts are very similar to line charts. They accept the same datasets and only define another default dataset display type and axis label renderer.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphBarChart();
  5. $graph->title = 'Wikipedia articles';
  6. // Add data
  7. foreach ( $wikidata as $language => $data )
  8. {
  9. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  10. }
  11. $graph->render( 400, 150, 'tutorial_bar_chart.svg' );
  12. ?>

As you can see in line 6, we only change the chart constructor, and the other default values are applied.

Simple bar chart

Lots of bars

By default, ezcGraph reduces the amount of steps shown on an axis to about 10 steps. This may cause unexpected results when trying to draw a bar chart with more than 10 bars in one dataset. You may override the behaviour by manually setting the amount of steps on the x axis:

  1. <?php
  2. // Initialize graph ...
  3. $graph->xAxis->labelCount = count( $chart->data['name'] );
  4. // Output graph ...
  5. ?>

This works because all datasets implement the Countable interface. If you want to use it for more than one dataset, you could do the following:

  1. <?php
  2. // Initialize graph ...
  3. $chart->xAxis->labelCount = max(
  4. count( $chart->data['name 1'] ),
  5. count( $chart->data['name 2'] )
  6. );
  7. // Output graph ...
  8. ?>

Combining bar and line charts

The only difference between bar and line charts is the display type of the dataset and the axis label renderer of the x-axis. You can use one of those constructors and modify your chart to display one or more datasets in either display type. The axis label renderer is described later in this tutorial.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphBarChart();
  5. $graph->title = 'Wikipedia articles';
  6. // Add data
  7. foreach ( $wikidata as $language => $data )
  8. {
  9. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  10. }
  11. $graph->data['German']->displayType = ezcGraph::LINE;
  12. $graph->options->fillLines = 210;
  13. $graph->render( 400, 150, 'tutorial_bar_line_chart.svg' );
  14. ?>

After creating the datasets we modify one of the datasets in line 14 to change the default display type to ezcGraph::LINE. To more prominently display the line, we set one graph option in line 16. Options are accessed like public properties and in this case we set an option for the graph called "fillLines", which indicates what transparency value is used to fill the space underneath the line.

Combined bar and line chart

More bar chart options

There are some more options available for line and bar charts, which configure the highlighting of datasets.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphBarChart();
  5. $graph->title = 'Wikipedia articles';
  6. // Add data
  7. foreach ( $wikidata as $language => $data )
  8. {
  9. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  10. }
  11. $graph->data['German']->displayType = ezcGraph::LINE;
  12. $graph->data['German']->highlight = true;
  13. $graph->data['German']->highlight['Mar 2006'] = false;
  14. $graph->options->fillLines = 210;
  15. $graph->options->highlightSize = 12;
  16. $graph->options->highlightFont->background = '#EEEEEC88';
  17. $graph->options->highlightFont->border = '#000000';
  18. $graph->options->highlightFont->borderWidth = 1;
  19. $graph->render( 400, 150, 'tutorial_bar_options.svg' );
  20. ?>

In line 20, the size of the highlight boxes is specified and lines 22 to 24 change the font configuration for the highlight boxes. Highlighting works in much the same way as for pie charts, but in line and bar charts it makes sense to highlight a complete dataset instead of only one single data point. This is because there is usually more than one dataset in line and bar charts.

Configured highlight in combined line and bar chart

Stacked bar charts

In stacked bar charts, the bars are not drawn next to each other, but aggregated in one bar, and the overall bar consumes the space of the sum of all single bars.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphBarChart();
  5. $graph->title = 'Wikipedia articles';
  6. // Stack bars
  7. $graph->options->stackBars = true;
  8. // Add data
  9. foreach ( $wikidata as $language => $data )
  10. {
  11. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  12. }
  13. $graph->yAxis->label = 'Thousand articles';
  14. $graph->render( 400, 150, 'tutorial_stacked_bar_chart.svg' );
  15. ?>

To use stacked bar charts, you only need to set the option $stackBars to "true". In the 3D renderer this will cause all bars to be rendered with the symbol ezcGraph::NO_SYMBOL.

Bar chart with stacked bars

Radar charts

Radar charts are very similar to line charts, but only with one axis, which will be drawn multiple times, rotated around the center point of the chart.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphRadarChart();
  5. $graph->title = 'Wikipedia articles';
  6. $graph->options->fillLines = 220;
  7. // Add data
  8. foreach ( $wikidata as $language => $data )
  9. {
  10. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  11. $graph->data[$language][] = reset( $data );
  12. }
  13. $graph->render( 400, 150, 'tutorial_radar_chart.svg' );
  14. ?>

This again is one of the simplest ways to create a radar chart. Nearly all options described later are also available in radar charts. The basic difference is that an ezcGraphRadarChart object is created in line 6. Radar charts accept multiple datasets, like bar and line charts. In line 14 the first element of the dataset is reassigned as the last element to close the circle. By not reassigning this value, you can get a radar chart where the tails do not join.

Simple radar chart

Controlling radar axis

Instead of having an x and a y axis, the radar chart has a main axis, which is the equivalent to the y axis in the other charts, and a rotation axis, the equivalent of the x axis. The steps on the rotation axis define the positions of the rotated main axis. This way you may use all available datasets and axes.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphRadarChart();
  5. $graph->palette = new ezcGraphPaletteEzBlue();
  6. $graph->options->fillLines = 220;
  7. $graph->legend->position = ezcGraph::BOTTOM;
  8. $graph->rotationAxis = new ezcGraphChartElementNumericAxis();
  9. $graph->rotationAxis->majorStep = 2;
  10. $graph->rotationAxis->minorStep = .5;
  11. mt_srand( 5 );
  12. $data = array();
  13. for ( $i = 0; $i <= 10; $i++ )
  14. {
  15. $data[$i] = mt_rand( -5, 5 );
  16. }
  17. $data[$i - 1] = reset( $data );
  18. $graph->data['random data'] = $dataset = new ezcGraphArrayDataSet( $data );
  19. $average = new ezcGraphDataSetAveragePolynom( $dataset, 4 );
  20. $graph->data[(string) $average->getPolynom()] = $average;
  21. $graph->data[(string) $average->getPolynom()]->symbol = ezcGraph::NO_SYMBOL;
  22. $graph->data[(string) $average->getPolynom()]->color = '#9CAE86';
  23. $graph->render( 500, 250, 'tutorial_complex_radar_chart.svg' );
  24. ?>

The settings on the graph will be explained later in the tutorial in detail. In line 11 the type of the rotation axis is set to a numeric axis, which is explained in Chart elements -> Axis.

For line 15 to 23, a dataset is added with some random data. Using this data as a base, a new dataset is built, which calculates a polynomial interpolation function. This is described in more detail in the section Datasets -> Average polynomial dataset. Lastly, the default colors and symbols from the palette are modified.

Complex radar chart

The resulting radar chart shows how minor steps on the rotation axis are drawn as a grayed out axis and major steps as a regular axis. Note that all types of datasets can be drawn using radar charts.

Odometer charts

Odometer charts can display values on one bar with a gradient and markers, providing a nice way for the viewer to detect where a value is in a defined bounding.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphOdometerChart();
  4. $graph->title = 'Sample odometer';
  5. $graph->options->font->maxFontSize = 12;
  6. $graph->data['data'] = new ezcGraphArrayDataSet(
  7. array( 1, 3, 9 )
  8. );
  9. $graph->render( 400, 150, 'tutorial_odometer_chart.svg' );
  10. ?>

As you can see from the example, the odometer basically behaves like other chart types. First we create an object of the class ezcGraphOdometerChart, then a title and a dataset is assigned, as per usual. Similar to pie charts, an odometer only accepts one dataset. A legend does not exist for odometers - and you may of course assign an array dataset, containing only one element.

Simple odometer

The result is a bar, filled with the default gradient, with markers as indicators for the values on the bar. The axis span is automatically calculated for the provided values - you can modify them as usual, but take a look at the next example for this.

Custom odometer chart

When using only one value on an odometer chart, you may wish to manually configure the span on the axis. You can do this as you normally would with any other axis.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphOdometerChart();
  4. $graph->title = 'Custom odometer';
  5. $graph->data['data'] = new ezcGraphArrayDataSet(
  6. array( 87 )
  7. );
  8. // Set the marker color
  9. $graph->data['data']->color[0] = '#A0000055';
  10. // Set colors for the background gradient
  11. $graph->options->startColor = '#2E3436';
  12. $graph->options->endColor = '#EEEEEC';
  13. // Define a border for the odometer
  14. $graph->options->borderWidth = 2;
  15. $graph->options->borderColor = '#BABDB6';
  16. // Set marker width
  17. $graph->options->markerWidth = 5;
  18. // Set space, which the odometer may consume
  19. $graph->options->odometerHeight = .7;
  20. // Set axis span and label
  21. $graph->axis->min = 0;
  22. $graph->axis->max = 100;
  23. $graph->axis->label = 'Coverage ';
  24. $graph->render( 400, 150, 'tutorial_custom_odometer_chart.svg' );
  25. ?>

In this example we only assign one value, so we get one marker on the odometer. The we start using the configuration options for odometers, defined in the ezcGraphOdometerChartOptions class.

The start and end color define the colors used for the background gradient. The border options define the border, which is drawn around the chart gradient. After this you can configure the width of the markers, and the space used for the actual odometer.

We then configure the minimum and maximum values for the axis and a label for the axis.

Custom configured odometer

Palettes

ezcGraph offers graph palettes to define the overall style properties of chart elements. The style properties are similar to those from CSS:

  • color
  • background color
  • border color
  • border width
  • padding
  • margin
  • dataset symbols

There are several predefined palettes in ezcGraph, but you can easily modify them or create your own palettes.

Using a predefined palette

You can assign each class extending ezcGraphPalette to the palette property of your graph. You should do this before adding datasets, because the datasets request colors from the palette. If you set the palette after creating the datasets, the datasets will still use the colors from the default palette.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphBarChart();
  5. $graph->palette = new ezcGraphPaletteBlack();
  6. $graph->title = 'Wikipedia articles';
  7. // Add data
  8. foreach ( $wikidata as $language => $data )
  9. {
  10. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  11. }
  12. $graph->data['German']->displayType = ezcGraph::LINE;
  13. $graph->options->fillLines = 210;
  14. $graph->render( 400, 150, 'tutorial_user_palette.svg' );
  15. ?>

The generated output differs quite a lot from the output using the default Tango palette. The colors for the background, datasets and fonts have been changed. Additionally, the palette sets a color for the major and minor grid, and defines a border width and color for the chart elements. The palette defaults to a sans-serif font and increases the margin between the chart elements.

Combined bar / line chart with non default palette

You can find a complete list of the available palettes in the class tree.

Modifying a palette

In the last example, we assigned a palette object to the palette property of the graph. You can of course create and modify the object before assigning it.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. require_once 'tutorial_custom_palette.php';
  4. $wikidata = include 'tutorial_wikipedia_data.php';
  5. $graph = new ezcGraphBarChart();
  6. $graph->palette = new tutorialCustomPalette();
  7. $graph->title = 'Wikipedia articles';
  8. // Add data
  9. foreach ( $wikidata as $language => $data )
  10. {
  11. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  12. }
  13. $graph->data['German']->displayType = ezcGraph::LINE;
  14. $graph->options->fillLines = 210;
  15. $graph->render( 400, 150, 'tutorial_modified_palette.svg' );
  16. ?>

The palette object is created in line 6 and we overwrite some of its properties. An overview on all available properties can be found in the class documentation for the abstract class ezcGraphPalette. In this example we just set two colors for the automatic colorization of the datasets and three symbols for datasets.

Since we assign more than two datasets, the first assigned color will be reused for the third dataset. You can see the usage of the symbols in the legend and on the line chart. The line chart displays a symbol for each data point if the symbol is set to something other than ezcGraph::NO_SYMBOL.

Combined bar / line chart with modified palette

Creating a custom palette

To style the graphs to fit a custom look, such as a corporate identity, the easiest way is to create your own palette. To create a custom palette you can either extend one of the predefined palettes and overwrite their properties or extend the abstract palette class.

  1. <?php
  2. class tutorialCustomPalette extends ezcGraphPalette
  3. {
  4. protected $axisColor = '#000000';
  5. protected $majorGridColor = '#000000BB';
  6. protected $dataSetColor = array(
  7. '#4E9A0688',
  8. '#3465A4',
  9. '#F57900'
  10. );
  11. protected $dataSetSymbol = array(
  12. ezcGraph::BULLET,
  13. );
  14. protected $fontName = 'sans-serif';
  15. protected $fontColor = '#555753';
  16. }
  17. ?>

Each undefined color will default to a transparent white. As you can see in the example definition, you can define alpha values beside the normal RGB values for the colors. After creating a custom palette, you can use it like any predefined palette, as previously explained.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. require_once 'tutorial_custom_palette_palette.php';
  4. $wikidata = include 'tutorial_wikipedia_data.php';
  5. $graph = new ezcGraphBarChart();
  6. $graph->palette = new tutorialCustomPalette();
  7. $graph->title = 'Wikipedia articles';
  8. // Add data
  9. foreach ( $wikidata as $language => $data )
  10. {
  11. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  12. }
  13. $graph->data['German']->displayType = ezcGraph::LINE;
  14. $graph->options->fillLines = 210;
  15. $graph->render( 400, 150, 'tutorial_custom_palette.svg' );
  16. ?>

The example now uses the custom palette to format the output. You can include palettes using your application's autoload mechanism or require them as shown in the example above.

Combined bar / line chart with custom palette

Chart elements

The chart elements all extend ezcGraphChartElement. Each of the elements can be configured independently. A default chart consists of the following elements:

  • title
  • background
  • legend
  • xAxis
  • yAxis

The palette defines the default formatting of the elements. Not only can you set foreground and background colors for all the elements, but you can also define their position in the chart or prevent them from being rendered at all.

Font configuration

We try to fulfill two goals regarding font configuration. First, there should be a single point to configure the fonts used for the text areas in the chart. On the other hand, it should be possible to configure the fonts independently for each chart element.

The solution is that you can modify the global font configuration by accessing $graph->options->font. This takes effect on all chart elements unless you intentionally access the font configuration of an individual chart element. The following section shows an example of this.

The chart title

The chart title element will only be rendered if you manually assign a title. It can be placed on top or at the bottom of the chart.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphPieChart();
  4. $graph->palette = new ezcGraphPaletteEzBlue();
  5. $graph->title = 'Access statistics';
  6. $graph->options->font->name = 'serif';
  7. $graph->title->background = '#EEEEEC';
  8. $graph->title->font->name = 'sans-serif';
  9. $graph->options->font->maxFontSize = 8;
  10. $graph->data['Access statistics'] = new ezcGraphArrayDataSet( array(
  11. 'Mozilla' => 19113,
  12. 'Explorer' => 10917,
  13. 'Opera' => 1464,
  14. 'Safari' => 652,
  15. 'Konqueror' => 474,
  16. ) );
  17. $graph->render( 400, 150, 'tutorial_chart_title.svg' );
  18. ?>

The chart title is the simplest element. In line 9, we change the global font configuration to use a serif font. In the SVG renderer, only the font name is relevant, because it is up to the client to actually render the bitmap from the defined vector definitions.

In line 11, we access the font configuration of the title element and change it back to use a sans-serif font. From now on, no change on the global font configuration will affect the title's font configuration. In line 14, we set a maximum font size, which now only affects the legend and the pie chart captions.

Aside from the font configuration, we set an option for all chart elements in line 11 - the background color of the current element. This results in a gray background for the title element only.

Font and title configuration in pie chart

The background element

With all drivers except the Ming (Flash) driver, you can set background images with the option to repeat them in the same way as in CSS definitions.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphPieChart();
  4. $graph->palette = new ezcGraphPaletteEzRed();
  5. $graph->title = 'Access statistics';
  6. $graph->data['Access statistics'] = new ezcGraphArrayDataSet( array(
  7. 'Mozilla' => 19113,
  8. 'Explorer' => 10917,
  9. 'Opera' => 1464,
  10. 'Safari' => 652,
  11. 'Konqueror' => 474,
  12. ) );
  13. $graph->background->image = 'ez.png';
  14. $graph->background->position = ezcGraph::BOTTOM | ezcGraph::RIGHT;
  15. $graph->background->repeat = ezcGraph::NO_REPEAT;
  16. $graph->render( 400, 150, 'tutorial_chart_background.svg' );
  17. ?>

In line 17, we set a background image, and define its position in line 18. You can use every combination of bottom / center / top with left / middle / right here, and it defaults to center | middle. In line 19, you set the type of repetition of the background image. This can be ezcGraph::NO_REPEAT or a combination of ezcGraph::HORIZONTAL and ezcGraph::VERTICAL. In this case, we just want a logo to be placed at the bottom right corner of the image.

With the SVG driver, the image is inlined using a data URL with the base64 encoded content of the binary image file. Using this driver, you do not need to worry about the locations of your referenced images.

With the GD driver, super sampling is not applied to the images, as this would make them blurry.

Pie chart with logo in background

Of course, you could also apply the following settings to the background element: background color, borders, margins and padding.

The legend

The legend is shown by default and is automatically generated from the assigned data. If you want to disable the legend, you can do this by setting it to "false" (line 9).

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphPieChart();
  4. $graph->palette = new ezcGraphPaletteEzGreen();
  5. $graph->title = 'Access statistics';
  6. $graph->legend = false;
  7. $graph->data['Access statistics'] = new ezcGraphArrayDataSet( array(
  8. 'Mozilla' => 19113,
  9. 'Explorer' => 10917,
  10. 'Opera' => 1464,
  11. 'Safari' => 652,
  12. 'Konqueror' => 474,
  13. ) );
  14. $graph->render( 400, 150, 'tutorial_chart_legend.svg' );
  15. ?>
Pie chart without legend

Legend configuration options

Other than hiding the legend, you can also place it at the bottom, left or top in the chart; you can assign a title for the legend and change the symbol sizes; you can additionally set the legend size.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphPieChart();
  4. $graph->palette = new ezcGraphPaletteEz();
  5. $graph->title = 'Access statistics';
  6. $graph->data['Access statistics'] = new ezcGraphArrayDataSet( array(
  7. 'Mozilla' => 19113,
  8. 'Explorer' => 10917,
  9. 'Opera' => 1464,
  10. 'Safari' => 652,
  11. 'Konqueror' => 474,
  12. ) );
  13. $graph->legend->position = ezcGraph::BOTTOM;
  14. $graph->legend->landscapeSize = .3;
  15. $graph->legend->title = 'Legend';
  16. $graph->render( 400, 150, 'tutorial_legend_options.svg' );
  17. ?>

To place the legend at another position on the graph, set the position property of the legend, as shown in line 17. If the legend is placed at the top or bottom, it will automatically use a landscape format. The space consumed by the legend is configured by the landscapeSize setting for landscape-oriented legends and the portraitSize setting otherwise. The assigned value is the percent portion of space taken up by the legend, relative to the size of the chart. The legend only displays a title if you manually set it, as shown in line 19.

Legend configuration example

Axis

The axis defines the unit scale in line and bar charts. There are always two axes - the x-axis and the y-axis, whose ranges are automatically received from the datasets and scaled to display appropriate values.

There are different types of values to display for both the x-axis and the y-axis. ezcGraph supports different axis types for different types of data. For normal string keys, the standard labeled axis is usually the right choice. The numeric axis is predestined to display numeric data, and the date time axis is for data associated with dates or times. All of the axis types can be assigned to either axis.

Labeled axes

The labeled axis is default for the x-axis in both bar and line charts. It is intended to display string labels of datasets and uses the centered label renderer by default. You saw it in all the earlier examples with bar and line charts, but it can be used for both axes as well.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphLineChart();
  5. $graph->options->fillLines = 210;
  6. $graph->options->font->maxFontSize = 10;
  7. $graph->title = 'Error level colors';
  8. $graph->legend = false;
  9. $graph->yAxis = new ezcGraphChartElementLabeledAxis();
  10. $graph->yAxis->axisLabelRenderer->showZeroValue = true;
  11. $graph->yAxis->label = 'Color';
  12. $graph->xAxis->label = 'Error level';
  13. // Add data
  14. $graph->data['colors'] = new ezcGraphArrayDataSet(
  15. array(
  16. 'info' => 'blue',
  17. 'notice' => 'green',
  18. 'warning' => 'orange',
  19. 'error' => 'red',
  20. 'fatal' => 'red',
  21. )
  22. );
  23. $graph->render( 400, 150, 'tutorial_axis_labeled.svg' );
  24. ?>

You could argue whether such a chart is really useful - but it works. Instead of using numeric values, colors are assigned when creating the dataset. The labeled axis uses the values in the order they are assigned. Line 11 is the first time we actually configure the axis label renderer. The axis label renderer describes how the labels are placed on the axis - the labeled axis uses the centered axis label renderer by default, which places the labels centered next to the steps on the axis. The setting in line 11 forces the renderer to show the zero value, even though it interferes with the axis.

Two labeled axes

Numeric axis

The numeric axis is the default for the y-axis. It displays numeric data and automatically determines appropriate scaling for the assigned values. However, you can also configure all scaling parameters manually.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphLineChart();
  5. $graph->title = 'Some random data';
  6. $graph->legend = false;
  7. $graph->xAxis = new ezcGraphChartElementNumericAxis();
  8. $graph->xAxis->min = -15;
  9. $graph->xAxis->max = 15;
  10. $graph->xAxis->majorStep = 5;
  11. $data = array(
  12. array(),
  13. array()
  14. );
  15. for ( $i = -10; $i <= 10; $i++ )
  16. {
  17. $data[0][$i] = mt_rand( -23, 59 );
  18. $data[1][$i] = mt_rand( -23, 59 );
  19. }
  20. // Add data
  21. $graph->data['random blue'] = new ezcGraphArrayDataSet( $data[0] );
  22. $graph->data['random green'] = new ezcGraphArrayDataSet( $data[1] );
  23. $graph->render( 400, 150, 'tutorial_axis_numeric.svg' );
  24. ?>

In this example, we force both axes to be numeric axes in line 10. In lines 12 to 15, we manually set the scaling options for the x-axis. We do not set a minorStep size here, so it will be automatically calculated from the other values, as will the settings for the y-axis. Then, we create some random data and create two datasets from it as usual.

Two numeric axes with random data

The example shows one advantage of a numeric axis over a labeled axis for numeric data. The axes are moved away from the chart's border to display the negative values below and left of the axis.

Date time axis

Previously in this tutorial, we used a labeled axis for date time data on the x-axis in the Wikipedia examples. This works fine for evenly-distributed time spans. For other data, you should use the date time axis.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $graph = new ezcGraphLineChart();
  4. $graph->options->fillLines = 210;
  5. $graph->title = 'Concurrent requests';
  6. $graph->legend = false;
  7. $graph->xAxis = new ezcGraphChartElementDateAxis();
  8. // Add data
  9. $graph->data['Machine 1'] = new ezcGraphArrayDataSet( array(
  10. '8:00' => 3241,
  11. '8:13' => 934,
  12. '8:24' => 1201,
  13. '8:27' => 1752,
  14. '8:51' => 123,
  15. ) );
  16. $graph->data['Machine 2'] = new ezcGraphArrayDataSet( array(
  17. '8:05' => 623,
  18. '8:12' => 2103,
  19. '8:33' => 543,
  20. '8:43' => 2034,
  21. '8:59' => 3410,
  22. ) );
  23. $graph->data['Machine 1']->symbol = ezcGraph::BULLET;
  24. $graph->data['Machine 2']->symbol = ezcGraph::BULLET;
  25. $graph->render( 400, 150, 'tutorial_axis_datetime.svg' );
  26. ?>

You can use timestamps or date time strings as dataset keys. The strings will be converted using PHP's strtotime() function.

Date axis example

Axis label renderer

As mentioned earlier in this tutorial, the axis label renderer defines where a label is drawn relative to the step on the axis. You already saw examples for all available axis label renderers, but here is an overview:

  • ezcGraphAxisExactLabelRenderer

    This is the default renderer for the numeric axis. The labels are drawn directly below the axis step. This may look strange sometimes, because it is not always possible to draw all labels of one axis on one side of the step; the last or first label would exceed the available space for the axis, and be rendered on the other side.

  • ezcGraphAxisCenteredLabelRenderer

    This renderer is the default for the labeled axis in line charts and draws the label centered next to the step. Therefore, this renderer omits the label for the initial step on the axis (0, 0) by default. However, this can be forced as shown in the example in Axis -> Labeled axes. The label is omitted because it would interfere with the axis or the labels of the other axis, and thus be difficult to read.

  • ezcGraphAxisBoxedLabelRenderer

    This is the default renderer for the labeled axis in bar charts. The steps on the axis and the grid are not drawn at the position of the label, but between two labels. This helps to recognize which bars belong together. Labels are rendered centered between two steps on the axis.

Rotated labels on axis

There is one more new axis label renderer since version 1.1 of ezcGraph - ezcGraphAxisRotatedLabelRenderer, which enables you to render rotated labels on an axis.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphLineChart();
  5. $graph->title = 'Wikipedia articles';
  6. $graph->xAxis->axisLabelRenderer = new ezcGraphAxisRotatedLabelRenderer();
  7. $graph->xAxis->axisLabelRenderer->angle = 45;
  8. $graph->xAxis->axisSpace = .2;
  9. // Add data
  10. foreach ( $wikidata as $language => $data )
  11. {
  12. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  13. }
  14. $graph->data['German']->displayType = ezcGraph::LINE;
  15. $graph->options->fillLines = 210;
  16. $graph->render( 400, 150, 'tutorial_rotated_labels.svg' );
  17. ?>

In line 9, a custom renderer is defined for the labeled x axis. You can assign custom axis label renderers on the property $axisLabelRenderer for ezcGraphChartElementAxis objects.

The renderer used in this example has custom properties like the rotation of the labels, which is set in degrees, while the rotation direction depends on the direction of the axis.

It makes sense to define more vertical space below the axis for the rotated labels as done in line 11 of the above example.

Date axis example

The results conatins rotated labels, which enables you to pack a lot more labels on one axis.

Additional axis & markers

Aside from the x axis and the y axis, you can add additional axes and markers to one chart. You can also assign these additional axes to datasets, so that some datasets use different axes than others.

Add markers to chart

First, add some markers, which only get a label and reside at some user defined position, to a chart. You may use them to display data boundings on the y axis, or important values on the x axis.

  1. <?php
  2. require_once 'tutorial_autoload.php';
  3. $wikidata = include 'tutorial_wikipedia_data.php';
  4. $graph = new ezcGraphLineChart();
  5. $graph->title = 'Wikipedia articles';
  6. // Add data
  7. foreach ( $wikidata as $language => $data )
  8. {
  9. $graph->data[$language] = new ezcGraphArrayDataSet( $data );
  10. }
  11. $graph->additionalAxis['border'] = $marker = new ezcGraphChartElementNumericAxis( );
  12. $marker->position = ezcGraph::LEFT;
  13. $marker->chartPosition = 1 / 3;
  14. $marker->label = 'One million!';
  15. $graph->render( 400, 150, 'tutorial_line_chart_markers.svg' );
  16. ?>

You can see a standard line chart, like in the examples before, using the Wikipedia datasets. In line 15 we add another axis, and configure this one in the following lines. The position of an axis defines its origin. The position ezcGraph::LEFT means that the axis starts at the left side of the graph. You can also use ezcGraph::RIGHT to make the axis start on the right.

The position of the axis may be defined by a float value, which defines the fractional position in the chart, calculated from the top left position. After this we also define a label for the axis.

Line chart with marker