154
JpGraph Manual 1 About this manual ............................................................................................................................................1 1.1 Version history ...................................................................................................................................1 1.2 How was this manual produced? .......................................................................................................1 2 Introduction ......................................................................................................................................................2 2.1 Version ...............................................................................................................................................2 2.2 Software License ................................................................................................................................2 2.3 JpGraph Features...............................................................................................................................2 2.4 Getting the latest version..................................................................................................................3 2.5 Planned future addition ......................................................................................................................3 2.6 Known bugs and omissions...............................................................................................................4 2.7 Acknowledgements ...........................................................................................................................4 2.8 A note on Implementing an OO library in PHP4 ...............................................................................4 2.9 Reporting bugs and suggesting improvements ..................................................................................5 3 Installation ........................................................................................................................................................6 3.1 Preparation .........................................................................................................................................6 3.2 Customizing the installation..............................................................................................................6 3.3 Required files ....................................................................................................................................7 3.3.1 Plot extension modules ......................................................................................................7 3.4 Graphic libraries requirements for PHP 4.02 and above ...................................................................7 3.5 Detailed steps to install JpGraph ........................................................................................................8 3.6 Troubleshooting your installation ......................................................................................................8 4 Working with jpGraph .................................................................................................................................10 4.1 What you will learn in this chapter ..................................................................................................10 4.2 How to generate images with PHP ..................................................................................................10 4.3 The basic principle of JpGraph and the creation of images .............................................................11 4.4 Chosing the image format for JpGraph ...........................................................................................12 4.5 Alternatives to streaming back the image ........................................................................................12 4.6 Working with fonts in JpGraph .......................................................................................................13 4.6.1 Installing TrueType fonts .................................................................................................13 4.6.2 Specifying fonts ...............................................................................................................13 4.6.3 Adding additional fonts to JpGraph .................................................................................15 4.7 Specifying colors in JpGraph ...........................................................................................................15 4.7.1 Available named colors...................................................................................................16 4.7.2 Theme colors for pie:s .....................................................................................................21 5 Understanding the JpGraph caching system..............................................................................................23 5.1 Enabling the cache system ...............................................................................................................23 5.2 Using the cache in your script ..........................................................................................................23 5.3 Some final comments .......................................................................................................................24 6 Introducing X-Y plot type ...........................................................................................................................25 6.1 Common feature for all graphs ........................................................................................................25 6.1.1 Commonly used properties .............................................................................................25 6.1.2 Commonly used methods ................................................................................................25 6.2 Line plots.........................................................................................................................................25 6.2.1 Adding plot marks to line-plots XXX .............................................................................28 6.2.2 Displaying the values for each data point ........................................................................29 6.2.3 Adding several plots to the same graph ...........................................................................30 6.2.4 Adding a second Y-scale................................................................................................31

Jpgraph Manual

Embed Size (px)

Citation preview

Page 1: Jpgraph Manual

JpGraph Manual1 About this manual............................................................................................................................................1

1.1 Version history...................................................................................................................................11.2 How was this manual produced?.......................................................................................................1

2 Introduction......................................................................................................................................................22.1 Version...............................................................................................................................................22.2 Software License................................................................................................................................22.3 JpGraph Features...............................................................................................................................22.4 Getting the latest version..................................................................................................................32.5 Planned future addition......................................................................................................................32.6 Known bugs and omissions...............................................................................................................42.7 Acknowledgements...........................................................................................................................42.8 A note on Implementing an OO library in PHP4...............................................................................42.9 Reporting bugs and suggesting improvements..................................................................................5

3 Installation........................................................................................................................................................63.1 Preparation.........................................................................................................................................63.2 Customizing the installation..............................................................................................................63.3 Required files....................................................................................................................................7

3.3.1 Plot extension modules......................................................................................................73.4 Graphic libraries requirements for PHP 4.02 and above...................................................................73.5 Detailed steps to install JpGraph........................................................................................................83.6 Troubleshooting your installation......................................................................................................8

4 Working with jpGraph.................................................................................................................................104.1 What you will learn in this chapter..................................................................................................104.2 How to generate images with PHP..................................................................................................104.3 The basic principle of JpGraph and the creation of images.............................................................114.4 Chosing the image format for JpGraph...........................................................................................124.5 Alternatives to streaming back the image........................................................................................124.6 Working with fonts in JpGraph.......................................................................................................13

4.6.1 Installing TrueType fonts.................................................................................................134.6.2 Specifying fonts...............................................................................................................134.6.3 Adding additional fonts to JpGraph.................................................................................15

4.7 Specifying colors in JpGraph...........................................................................................................154.7.1 Available named colors...................................................................................................164.7.2 Theme colors for pie:s.....................................................................................................21

5 Understanding the JpGraph caching system..............................................................................................235.1 Enabling the cache system...............................................................................................................235.2 Using the cache in your script..........................................................................................................235.3 Some final comments.......................................................................................................................24

6 Introducing X−Y plot type...........................................................................................................................256.1 Common feature for all graphs........................................................................................................25

6.1.1 Commonly used properties.............................................................................................256.1.2 Commonly used methods................................................................................................25

6.2 Line plots.........................................................................................................................................256.2.1 Adding plot marks to line−plots XXX.............................................................................286.2.2 Displaying the values for each data point........................................................................296.2.3 Adding several plots to the same graph...........................................................................306.2.4 Adding a second Y−scale................................................................................................31

Page 2: Jpgraph Manual

JpGraph Manual6 Introducing X−Y plot type

6.2.5 Adding a legend to the graph...........................................................................................326.2.6 Handling null−values in lineplots....................................................................................346.2.7 Using the step−style to render line plots..........................................................................356.2.8 Using logarithmic scale...................................................................................................356.2.9 More on scales.................................................................................................................376.2.10 Adjusting the gridlines in the plot..................................................................................386.2.11 Specifying text labels for the X−axis.............................................................................396.2.12 Adjusting the ticks on a text scale.................................................................................406.2.13 Using filled line graphs..................................................................................................416.2.14 Using accumulated line graphs......................................................................................42

6.3 Bar graphs........................................................................................................................................436.3.1 Adjusting the width of the bars........................................................................................446.3.2 Displaying the value of each bar......................................................................................456.3.3 Adding a drop shadow to the bar.....................................................................................476.3.4 Adjusting the alignment of bars ona text scale................................................................476.3.5 Using grouped bar plots...................................................................................................476.3.6 Using accumulated bar plots............................................................................................496.3.7 Using grouped accumulated bar graphs...........................................................................496.3.8 Horizontal bar graphs.......................................................................................................506.3.9 Using gradient fill for bar graphs.....................................................................................546.3.10 Creating semi−filled bar graphs....................................................................................55

6.4 Error plots........................................................................................................................................566.4.1 Using line error plots.......................................................................................................57

6.5 Scatter plots......................................................................................................................................586.6 Combining different graph types.....................................................................................................616.7 Specifying the scale manually.........................................................................................................636.8 Adjsuting the automatic tick marks.................................................................................................646.9 Adjusting labels on a text scale........................................................................................................656.10 Adding arbitrary text strings to the graph......................................................................................686.11 Adding titles and footers to the Graph...........................................................................................706.12 Using background images..............................................................................................................716.13 Using callbacks for Plot marks......................................................................................................736.14 Formatting the axis........................................................................................................................75

6.14.1 Standard two axis graphs..............................................................................................756.14.2 Scientific style axis........................................................................................................776.14.3 Adjusting the position of the scale labels.....................................................................786.14.4 Formatting the scale labels............................................................................................786.14.5 Inverting the Y−axis......................................................................................................78

6.15 Adjusting the autoscaling limits − grace value..............................................................................796.16 Adding bands of pattern and color to graphs.................................................................................81

6.16.1 Customizing the patterns..............................................................................................826.17 Adding static lines to the plot.......................................................................................................84

7 Working with non X,Y−plots........................................................................................................................857.1 Radar plots.......................................................................................................................................85

7.1.1 Simple radar plots............................................................................................................867.1.2 Specifying titles for the axis and legends for the plots....................................................877.1.3 Adding gridline to the radar plot......................................................................................877.1.4 Adding several plots to the same radar graph..................................................................88

7.2 Pie plots............................................................................................................................................897.2.1 Creating 3D pie plots.......................................................................................................91

Page 3: Jpgraph Manual

JpGraph Manual7 Working with non X,Y−plots

7.2.2 Exploding pie slices.........................................................................................................927.2.3 Specifying and adjusting labels on pie plots....................................................................937.2.4 Specifying slice colors and using themes........................................................................947.2.5 Adding drop shadows to the slices..................................................................................957.2.6 Another variant of 2D Pie plots.......................................................................................95

8 Using image maps with JpGraph.................................................................................................................978.1 The basic structure of an image map script.....................................................................................978.2 Specifying targets for image map plots...........................................................................................978.3 Using StrokeCSIM()........................................................................................................................988.4 Examples of Image maps.................................................................................................................99

8.4.1 Client maps with Bar graphs............................................................................................998.4.2 Client maps with Pie graphs............................................................................................998.4.3 Client maps with Scatter graphs....................................................................................100

8.5 How does StrokeCSIM() work?.....................................................................................................1008.6 Getting hold of the image map.......................................................................................................1018.7 Image maps and the cache system.................................................................................................101

9 Gantt charts..................................................................................................................................................1029.1 Purpose of this tutorial...................................................................................................................1029.2 Some notes on format and files used in this tutorial......................................................................1029.3 Why use Gantt charts?...................................................................................................................1029.4 Capabilities in JpGraph Gantt module...........................................................................................1039.5 A simple Gantt chart......................................................................................................................1039.6 The structure of a Gantt chart.......................................................................................................1069.7 Creating a GanttChart....................................................................................................................1079.8 Positioning objects in the Gantt plot..............................................................................................1079.9 Gantt bars.......................................................................................................................................108

9.9.1 Specifying vertical position...........................................................................................1089.9.2 Specifying start and end position for a bar....................................................................1099.9.3 Milestones......................................................................................................................1109.9.4 Vertical line....................................................................................................................1129.9.5 Adding markers to a gantt bar........................................................................................1149.9.6 Adjusting the minimum distance between bars.............................................................115

9.10 Formatting the scale headers........................................................................................................1179.10.1 Day scale......................................................................................................................1199.10.2 Week scale...................................................................................................................1199.10.3 Month scale..................................................................................................................1209.10.4 Year scale.....................................................................................................................121

9.11 More formatting for bars..............................................................................................................1219.11.1 Adding caption to bars.................................................................................................1219.11.2 Adding progress indicators to bars..............................................................................122

9.12 More general Gantt formatting....................................................................................................1239.12.1 Adding a table title.......................................................................................................1239.12.2 Modifying the divider lines..........................................................................................1249.12.3 Modifying the box around the plot..............................................................................125

9.13 Advanced formatting...................................................................................................................1259.13.1 Showing only part of the graph....................................................................................1259.13.2 Specifying start day of week........................................................................................126

9.14 Localizing....................................................................................................................................126

Page 4: Jpgraph Manual

JpGraph Manual10 Miscellanies features..................................................................................................................................127

10.1 Anti−aliasing in JpGraph.............................................................................................................12710.1.1 Enabling anti−aliased lines..........................................................................................127

10.2 Rotating the graphs......................................................................................................................12810.3 Adjusting brightness and contrast for images and backgrounds..................................................12910.4 Timing the generation of graphs..................................................................................................131

11 Working with canvas graphs....................................................................................................................13311.1 Introduction..................................................................................................................................13411.2 Creating a simple canvas.............................................................................................................13511.3 Adding lines and rectangles to a canvas......................................................................................13711.4 Using a canvas scale....................................................................................................................13811.5 Sample application: Drawing DB schema...................................................................................142

12 Utilities in JpGraph..................................................................................................................................14812.1 Under the utils/misc directory.....................................................................................................14812.2 Under the utils/jpdcgen...............................................................................................................148

13 Code defines in JpGraph...........................................................................................................................149

Page 5: Jpgraph Manual

1 About this manual

1.1 Version history

Version Date Status Who Comment

R1.0 2002−10−05 Released Johan Persson Added additional info, proper indexing

D1.0 2002−09−16 Draft Johan Persson Initial version

1.2 How was this manual produced?

The bulk of the text was written directly in Emacs on a GNU/Linux system in a mixture of PHP and HTML.A number of PHP functions were used to automate the handling of formatting example code and figures.

To generate the images automatically in the img directory a custom awk−script is used to extract all the usedimage script from the manual. The sript then uses the text based HTML browser 'links' to render the PHPimage script non−interactively and then store them in the 'img' directory.

To finally generate all pure HTML pages from the PHP sources again 'links' was used together with a customMakefile.

The final set of HTML files was then processes by HTMLDOC to construct table of contents and chapterlinks.

The result of this process is what you are reading at the moment.

10/07/2002 01:19:24 AM 1

Page 6: Jpgraph Manual

2 Introduction

2.1 Version

This manual covers version 1.8 of JpGraph. A 2D graph plotting library for PHP 4.02 and above.

Note that this library will not work with versions prior to PHP 4.02 due to extension in the object model thatis used in this library.

2.2 Software License

JpGraph 1.x is released under a dual license QPL 1.0 (Qt−License) for non−commercial (includingeducational) use of the library and the JpGraph Professional License for commercial use.

2.2.0.1 Why is it not altogether free?

JpGraph is free software as in free speech but not as in free beer. Every hour I spend working on this librarymeans one less hour spend on my consultancy work needed to pay silly things like rent and food. If you are alarge company making use of the library in a commercial context you are both morally and legally bound toget the Professional JpGraph License.

The license fee corresponds to the cost for roughly 35 min of work for a professional IT consultant (averageaccording to IDG for 2002)

The professional version also contains additional features not available in the free version

Additional plot module for tachometer plots• Off−line class reference• PDF version of the documentation•

2.3 JpGraph Features

This is a truly OO graph library which makes it easy to both draw a "quick and dirty" graph with a minimumof code and quite complex graphs which requires a very fine grain of control. The library tries to assignsensible default values for most parameters hence making the learning curve quite flat since for most of thetime very few commands is required to draw graphs with a pleasing esthetical look.

Some highlights of available features are

Flexible scales, supports text−lin, text−log, lin−lin, lin−log, log−lin and log−log and integer scales.• Supports both PNG, GIF and JPG graphic formats. Note that the available formats are dependent onthe specific PHP installation where the library is used.

Supports caching of generated graphs to lessen burden of a HTTP server.• Supports batch mode to only generate images to a file• Supports client side image maps which makes it easy to produce drill down images.•

10/07/2002 01:19:24 AM 2

Page 7: Jpgraph Manual

Intelligent autoscaling which gravitates towards esthetical values, i.e. multiples of 2:s and 5:s• Fully supports manual scaling, with fine grain control of position of ticks.• Supports background images with different formatting options• Supports color and brightness adjustments of images directly in PHP.• User specified grace for autoscaling• Supports up to two different y−scale, it is possible to have different left and right y−scale and addplots to both

Supports, line−plots, filled line−plots, accumulated line−plots, bar plots, accumulated bar plots,grouped bar plots, error plots, line error plots, scatter plots, gantt−charts, radar plots, 2D and 3D piecharts.

Supports unlimited number of plots in each graph, makes it easy to compose complex graph whichconsists of several plot types

User specified position of axis• Supports color gradient fill in seven styles• Designed as a flexible OO framework which makes it easy to add new types of plots• Supports automatic legend generation• Supports both vertical and horizontal grids• Supports anti−alising of lines• Supports rotation of linear graphs• More then 400 named colors• Designed modularly − you don't have to include code which isn't used•

In addition to these high level features the library has been designed to be orthogonal and very coherent in its'naming convention. For example, to specify color each object (i.e. axis, grids, texts, titles etc) within the graphimplements the method SetColor() with the same signature.

2.4 Getting the latest version

The latest version of jpgraph can always be found on http://www.aditus.nu/jpgraph/

The current version as of this writing is 1.8

Note. I keep a straitforward version scheme to avoid the version number inflation. This means

1.x −> 1.x.1, Bug fix release for version 1.x• 1.x −> 1.(x+1), Added functionality. Mostly keeping backwards compatibility unless a very goodreason not to. All SC breaks will be well announced in release notes and might be small things like amisspelled method name compared to the proper english spelling.

1.x −> 2.0, Substantially new functionality which might break backward compatibility•

2.5 Planned future addition

All the following features, which have not been marked as tentatively, will be added. The timeframe for theseversions are:

Version 1.9, (January 2003) New image anti−aliasing• Version 2.0, (Summer 2003) Based on PHP builtin GD library.•

10/07/2002 01:19:24 AM 3

Page 8: Jpgraph Manual

No time frames have been determined for version 2.x and above. If you like these timeframes to moveforward either get involved in the development yourself or conside make a donation. Changes, bugfixes andadditions are always welcome. For the latest upate on planned future version see the web−site for JpGraph athttp://www.aditus.nu/jpgraph/

2.6 Known bugs and omissions

Negative bar graphs is not well tested and may have layout problem when displaying automaticvalues on top of them

Filled negative line plots does not work as expected• Background images does not work as expected for rotated graphs•

2.7 Acknowledgements

The idea for writing this library grew out of my own needs for a high quality graph drawing library for PHP4.Before reinventing the wheel I searched the net to see if there where anything already available that wouldmeet my needs. When searching I found three other PHP graph plotting libraries:

"chart 0.3" http://quimby.gnus.org/circus/chart/chart−0.3.tar.gz, by Lars Magne Ingebrigtsen1. "ykcee.php", http://ykcee.sourceforge.net2. "phplot.php", http://www.phplot.com3.

All these libraries implements some fine graphic features but unfortunately none of those completely fulfilledmy needs either for available functionality (for example none of these supported both two Y−scales,auto−scaling, and logarithmic scales), or general flexibility, I especially needed the option of two Y−scales,which none of the above packages supported. My own preference for design was closest to "chart 0.3" so Istarted by fixing some small bugs in that package and adding some new features. However I soon realized thatto add all the features and flexibility I wanted to "chart 0.3" it would require a complete rewrite since theoriginal design wasn't flexible enough, especially adding a second Y−scale would require a more flexible OOarchitecture. Since at the time I was also interested in giving PHP a try to see how well it would support afully object oriented design so I started designing this library. The library is completely written from scratchbut I have taken some ideas, especially the caching feature from "chart 0.3" and implemented this. I'mtherefore thankful for those ideas. Any bugs and faults within the code are completely my own.

2.8 A note on Implementing an OO library in PHP4

In terms of OO support PHP is still at loss to Java, Eiffel or C++ but since it always been my view that OOdesign is more a state of mind then of implementation details it is still possible to arrive with a decent OOdesign even in PHP. One of the big obstacles is probably the very different assigning semantics used by PHPas compared to other OO languages since it is always copies of the object that is passed around by default andnot references. This took some time for me personally to get used to (giving my own background in OOdesign in Java, Eiffel and C++). There is also a bug (present in all versions <=4.04pl1) that makes itimpossible to use a reference to the '$this' pointer in the constructor. This has an easy workaround by addingan extra method, say Init(), which is called immediately after the constructor and may safely use a reference to'$this' pointer. As an example of JpGraph's OO features this is, to my knowledge, the only piece of PHP codeto fully implement the Observer pattern.

10/07/2002 01:19:24 AM 4

Page 9: Jpgraph Manual

2.9 Reporting bugs and suggesting improvements

Bug reports and suggestions are always welcome. I only ask you to make sure that you read the requirementsand the FAQ before submitting bugs and making sure you have an up to date version of PHP4, the necessarygraphic libraries etc. I will unfortunately not be able to answer standard OO or PHP4 questions. Neither do Ihave the time to give PHP/GD/TTF/Apache installation support. Please see the corresponding documentationand relevant FAQ. I simply don't have the bandwith to help with these kinds of installations. Please note thatthis library will not work with versions prior to PHP4.02. Bug reports and suggestions should be sent [email protected]

10/07/2002 01:19:24 AM 5

Page 10: Jpgraph Manual

3 Installation

3.1 Preparation

In general the only thing you need to do is to make sure your PHP files can include the required library files(as described below) and that your PHP installation supports at least one graphic format, i.e. it supports the"image" extension to PHP.

You can easily verify this by making sure that your installation of PHP supports some of the 'imagecreate()'functions.

This means that you must have a working GD−library together with PHP before even thinking of runningJpGraph. Please make sure you have verion 4.02 or above of PHP since JpGraph will not work with versionsprior to PHP 4.02 that. Ideally you should use at least PHP 4.1.x

If you want to use TTF fonts you must also make sure that your PHP installation supports TTF fonts (eitherthrough FreeType 1 or FreeType 2 libraries). In additions to this you need at least a couple of TTF fonts. Inpreparation of using TTF fonts with JpGRaph you must specify, in jpgraph.php , where those font files can befound.

JpGraph uses a naming convention for the TTF font files in order to be able to find the correct font files. Youshould therefore use the font files that can be downloaded together with JpGraph.

In order to make sure that you have GD installed you could try by running the following example whichcreates a very simple image using just pure GD calls and outputs an image in PNG format.

header ("Content−type: image/png");$im = @ImageCreate (50, 100) or die ("Cannot create a new GD image.");$background_color = ImageColorAllocate ($im, 255, 255, 255);$text_color = ImageColorAllocate ($im, 233, 14, 91);ImageString ($im, 1, 5, 5, "A Simple Text String", $text_color);ImagePng ($im);

The above script must work before you will have any chance of getting JpGraph working.

3.2 Customizing the installation

In order for JpGraph to work you must adjust the cache and TTF directory to suit your installation. By defaultthe TTF directory is "/usr/local/fonts/ttf/" and for the cache "/tmp/jpgraph_cache/". These are defined as PHPdefines at the top of jpgraph.php

Please make sure that PHP has write permissions to the cache directory if you plan to use the cache feature. Ifnot you will get a "Can't write file xxx.yyy" error when you try to genereate a graph. You can read more abouthow to use the cache in the chapter Making sense of caching system in JpGraph

10/07/2002 01:19:24 AM 6

Page 11: Jpgraph Manual

3.3 Required files

This is the base library files, which you must have

Jpgraph.php, base library, always needed•

3.3.1 Plot extension modules

To add plots to the graph you will need one or more of the following files plot extension files dependiong onwhat kind of graph you need to create.

jpgraph_log.php, Plot extension to support logarithmic X and Y scales• jpgraph_line.php, Plot extension. Needed to draw various line plots• jpgraph_bar.php, Plot extension. Needed to draw various bar plots• jpgraph_error.php, Plot extension. Needed to draw various error plots• jpgraph_scatter.php, Plot extension. Needed to draw scatter and impuls plots.• jpgraph_spider.php, Plot extension. Needed to draw spider plots.• jpgraph_pie.php, Plot extension. Needed to draw Pie plots• jpgraph_pie3d.php, Plot extension. Needed to draw 3D Pie plots• jpgraph_gantt.php, Plot extension. Needed to create gantt plots• jpgraph_canvas.php, Plot extension to make it possible to draw arbitrary graphic on a canvas.• jpgraph_vanvtools.php, Add on to the canvas graph to privide an easier way to rdaw arbitrary shapes.•

3.4 Graphic libraries requirements for PHP 4.02 and above

Per default the standard GD image library supports PNG graphic formats. You will need to have that installedtogether with your PHP module for this library to work at all. Please refer to PHP documentation on specifics.Note that the newer versions of GD does not support the GIF format due to copyright problems. Hence bydefault only PNG is supported.

If you want JPEG support you will also need an additional library for PHP, again please see PHPdocumentation for specifics. For most practical purposes PNG is a better format since it normally achievesbetter compression then GIF (typically by a factor of 2 for the types of images generated by JpGraph). Incomparison with JPEG format PNG is also better for the type of images generated by this library. So, thebottom line is, you should have a very good reason to choose any other format then PNG.

By default the image format is set to "auto". This means that JpGraph automatically chooses the best availablegraphic using the preferred order "PNG", "GIF", "JPG".

Note: The reason that my site (www.aditus.nu) only displays GIF images is that my Web hotell doesn't support a newer version of GD which allows PNGformat. One of lifes small pains. This is the reason that I in most places just displays the PNG images directly in the img tag on my site without going throughJpgraph since the GIF format gives much bigger files and would make my site slower.

Sidenote 2: To get background images working with GD 2.0.1 you MUST enable Truecolor images by setting the constant USE_TRUECOLOR to true. If youdon't do this the background images will just be a black rectangle. The bad thing with this is that the antialias for Truetypes is broken using truecolor images inGD 2.0.1. This means you can't have background and TTF fonts in the same image.

You can find a bug fix for GD 2.01 and the TTF problem together with Truecolor images at

10/07/2002 01:19:24 AM 7

Page 12: Jpgraph Manual

http://www.coupin.net/gd−freetype/

NOTE: This bug fix has _nothing_ to do with JpGraph and I can't guarantee anything nor answer any questions regarding this specific fix.

3.5 Detailed steps to install JpGraphMake sure your PHP is AT LEAST 4.04 (preferrable 4.1.1) and that you have compiled support for GD library. You must make aboslutely surethat you have GD working. Please run phpinfo() to check if GD library is supported in your installation. Please not that JpGraph only fullysupports GD 1.x. There are known issues with GD 2.0.1 , see the notes section below.

1.

Unzip and copy the files to a directory of your choice.2. Set up the directory paths in jpgraph.php where the cache directory should be and where your TTF directory is. Note that Apache/PHP must havewrite permission in your cache directory.

3.

Check that all rest of the DEFINE in the top of JpGraph.php is setup to your preference. The default should be fine for most users. (See also Note5. below) Specifically check that the settings of USE_GD2_LIBRARY reflects your installation, (should be true if you have GD2 installed, falseotherwise).

4.

Make sure PHP have write privileges to your cache directory if you plan on using the cache feature.5. Some windows installations seems to have a problem with a PHP script ending in a newline (This newline seems to be sent to the browser and willcause a Header already sent error). If you have this problem try remove all trailing newlines in the jpgraph* files

6.

It has been reported that PHP 4.06 under IIS has problem correctly interpreting file paths. This can be solved by hardcoding theCACHE_DIRECTORY and FONT_DIRECTORY constants directly in the code instead of using the defined constants.

7.

Read (really!) the JpGraph FAQ.8.

3.6 Troubleshooting your installationAny PHP errors about function "imagecreate" does not exist indicates that your PHP installation does not include the GD library. This must bepresent.

1.

Any error about "parent::" undefined means that you are not using PHP 4.02 or above. You _NEED_ PHP 4.02 or higher. This problem has alsobeen reported to sometimes occur under Windows. This problem has also been reported by people running Zend−cache and is a bug in Zend. Aworkaround is to move all files into one single file.

2.

If you don't get any background images (but rather a solid black box) you are using GD 2.x but have forgotten to enable truecolor support. Correctthis by enabling the USE_TRUECOLOR define.

3.

If background images does not work make sure the settings of USE_GD2_LIBRARY corresponds to your installation, i.e. If you don't have GD2then this define must be false!

4.

If you are running PHP 4.06 and get an error saying "GD was not built with truetype support" you should know that this is a known problem withGD+PHP 4.06. There are some workarounds (search the net!) but it is really recommended that you instead upgrade to at least PHP 4.1.1 andconfigure PHP with −−with−gd−native−ttf (Please also note that the built in TTF uses point size for fonts whereas Truetype 2 uses pixels.) PleaseDON't ask me how to resolve the GD Font problem. All mail regarding this will go straight to /dev/null. Upgrade to 4.1.1!

5.

If you are running IIS and Win2k and get the error "Can't find font" when trying to use TTF fonts then try to change you paths to UNIX style, i.e."/usr/local/fonts/ttf/". Remember that the path is absolute and not relative to the htdocs catalogue.

6.

If you are using the cache please make sure that you have set the permissions correctly for the cache directory so that Apache/PHP can write to thatdirectory.

7.

If you have problem building GD 2.0.1 for PHP you might want to try the following tip from Rasmus L.8.

−−−−<QUOTE >−−−−

Build GD 2.0.1 with these two lines in your GD2 Makefile

CFLAGS=−g −DHAVE_LIBPNG −DHAVE_LIBJPEG −DHAVE_LIBFREETYPE LIBS=libgd.a −lpng −lz −ljpeg −freetype −lm

Don't install the lib anywhere, just leave it in the GD−2.1.1 directory.

Then build PHP using a minimum of:

−−with−gd=/home//gd−2.0.1 −−with−freetype−dir=/use −−enable−gd−native−ttf −−enable−gd−imgstrttf −−with−jpeg−dir=/usr −−with−png−dir=/usr

10/07/2002 01:19:24 AM 8

Page 13: Jpgraph Manual

−−with−xpm−dir=/usr/X11R6

The above assumes you have freetype2 installed along with the libjpeg and libpng libs under /usr

−−−− <END QUOTE >−−−−

10/07/2002 01:19:24 AM 9

Page 14: Jpgraph Manual

4 Working with jpGraph

4.1 What you will learn in this chapter

How to generate images in PHP with JpGraph1. How to choose the image encoding2. Various ways of using the generated image, streaming it back to the browser, sending it to a file orgetting hold of the image handle for further post processing

3.

How to specify fonts (both bit−mapped and TTF) in JpGraph4. How to extend JpGraph with your own fonts5. How to work with Cyrillic fonts6. How to specify colors in JpGraph7. List all available named colors in JpGraph8. How to effectively use the built in cache schema in JpGraph9.

4.2 How to generate images with PHP

As a general rule each PHP script which generates an image must be specified in a separate file which is thencalled in an <IMG> tag reference. For example, the following HTML excerpt includes the image generated bythe PHP script in "fig1.php".

<img src="fig1.php" border=0 align=center width=300 height=200>

The library will automatically generate the necessary headers to be sent back to the browser to correctlyrecognize the data stream as an image of either PNG/GIF/JPEG format. The browser can then correctlydecode the image

Observere that you can't return anything else than an image from the image script. By definition each HTMLpage can only consist of one mime type which is determined by the sent headers.

A common mistake is to have a space in the beginning of the image script file which the HTTP server willsend back to the browser. The browser now assumes that the data comming back from this script is normalASCII. When then the image headers get send back to the browser to forwarn the browser of theforthcomming image the browser will not like that. It has already determined that the script should only sendASCII data back and will then give you a "Headers already sent error".

To include several images together with text on a page you need to have a parent page with several <IMG>which each refers to an image script.

To get access to the library you will need to include at least two files, the base library and one or more of theplot extensions. So for example if you want to do line plots the top of your PHP file must have the lines:

10/07/2002 01:19:24 AM 10

Page 15: Jpgraph Manual

<?php

include ('jpgraph.php');include ('jpgraph_line.php');...// Code that uses the jpgraph library...

Sidebar: You might also use the PHP directive requires(). The difference is subtle in that include will only include the code if the include statement is actuallyexcuted. While require() will always be replaced by the file specified. See PHP documentation for further explanation. For most practical purposes they areidentical.

4.3 The basic principle of JpGraph and the creation of images

You will see that the common pattern for creating graphs is to

Create a script that constructs the image, type, colors size and so on.1. A wrapper script which contains one or more <IMG> tags to position the graphs on the proper HTMLpage.

2.

Of course it is of perfectly possible to call the image script directly in the browser to just display the generatedimage in the browser.

You shopuld remember that it is also possible to pass arguments to the image script via the normal HTTPparameters, for example

<img src="showgraph.php?a=1&b=2">

This could for example be used to control the apperance of the image or perhaps send data to the image whichwill be displayed. Note that this is probably not the best way to send large amount of data to plot. Instead theonly practical way, for large data sizes, is to get all the data in the image script, perhaps from a DB.

Tips: Forcing the browser to update your image Some browser may not send back a request to the web browser unless the user presses "Refresh" (F5 − inmost browsers). This can lead to problems that the user is seeing old data. A simple trick is to add a dummy time argument which is not used in the script. Forexample

echo "<img src='myimagescript.php?dummy=".now()."'>"

When it comes to the structure of your imaging script they will generally have the structure

// ... Include necessary headers

$graph = new Graph($width,$height, ...);

// ... code to construct the graph details

$graph−>Stroke();

10/07/2002 01:19:24 AM 11

Page 16: Jpgraph Manual

JpGraph is completely Object oriented so all calls will be action on specific instances of classes. One of thefundamental classes is the Graph() class which represents the entire graph.

After the creation of the Graph() object you add all your lines of code to construct the details of the graph.

As the final call you will send the generated image back to the browser with a call to the Stroke() method.

Note: This is not always true, but to keep things simple for the moment we assume this.

In addition to this standard usage pattern you can also send the graph directly to a file, get the GD imagehandler for the image and also make use of the builtin cache system. The cache system, which lessens theburden of the PHP server, works by avoiding o run all the code that follows the initial Graph() call bychecking if the image has already been created and in that case directly send back the previously created (andfiled) image to the browser. When using the cache system you must specify a filename which is used to storethe image in the cache system and possibly also a timeout value to indicate how long the image in the cachedirectory should be valid. For this reason you might in the following examples, for example, see the code

$graph = new Graph(300,200,"auto");

in the start of all the examples. The two first parameters specify the width and height of the graph and thethird parameter the name of the image file in the cache directory. The special name 'auto' indicates that theimage file will begiven the same name as the image script but with the extension changed to indicate thegraphic format used, i.e '.jpg', '.png' and so on.

4.4 Chosing the image format for JpGraph

By default JpGraph automatically chooses the image format to use in the order PNG, JPEG and GIF. The exact format depends on what is available on yoursystem. There are two ways you can influence the way the graphic format is choosen.

Change the default graphic format by changing the DEFINE

DEFINE("DEFAULT_GFORMAT","auto");

1.

Set the graphic format in your script by calling the method SetImgFormat() For example, to force your script to use JPEG in one specific imageuse

$graph−>img−>SetImgFormat("jpeg")

2.

4.5 Alternatives to streaming back the image

If you like to save the image directly to a file instead of streaming it back to the browser then you just have to specify an absolute filename in the final call toGraph::Stroke(), i.e.

$graph−>Stroke("/usr/home/peter/images/result2002.png");

Please note that the user running as Apache/PHP must have write access to the specified directory.

10/07/2002 01:19:24 AM 12

Page 17: Jpgraph Manual

There are also two predefined filenames which have special meaning.

"auto", This will create a file in the same directory as the script with the same name as the script but with the correct image extension.• _IMG_HANDLER, (This is defined in jpgraph.php). Specifying this filename will not create a an image to file or stram it back to the browser.Instead it will instruct the Stroke() method to just return the handle for the GD image. This is usefull if you later want to manipulate the image inways that are not yet supported by Jpgraph. For example include the image in generated PDF files.Example:

$handle = $graph−>Strokg(_IMG_HANDLER);

4.6 Working with fonts in JpGraph

JpGraph supports both a set of built in bit−mapped fonts as well as True Type Fonts. For scale values on axisit is strongly recommended that you just use the built in bitmap fonts for the simple reason that they are, formost people, easier to read (they are also quicker to render). Try to use TTF only for headlines and perhapsthe title for a graph and it's axis. By default the TTF will be drawn with anti−aliasing turned on.

In many of the example you can see examples of both TrueType and BitMap fonts.

There are a number of subtle differences in the way builtin fonts and TrueType fonts are rendered to thescreen. However, JpGraph, abstracts away 99.9% of the differences so it will be, for the user, completelytransparent to switch between the different fonts.

4.6.1 Installing TrueType fonts

Since Internally TrueType fonts are rendered by locating a font specification file you must install theaccompanying TrueType fonts in directory of your choice. You must then tell JpGraph where these fonts maybe found by specifying the font−path in the FONT_PATH defione (in jpgraph.php). Please note that this mustbe the absolute file path and not relative to the htdocs directory. By default the path is set to

DEFINE("TTF_DIR","/usr/local/fonts/ttf/");

Since JpGraph must be able to tell the difference between the italic and bold versions of the same font familya standard naming convention is used to name the files. The available fonts are also defined by DEFINES andhence you can't just copy your own TTF files to the directory and expect it to work. At the moment there is no"easy" way to add new fonts but to make some (small) mods to the code. However this is expected to changein future version of JpGraph.

4.6.2 Specifying fonts

All graph objects that uses text allows you to specify the font to be used by calling the SetFont() method andspecifying three parameters

Font family, Specified with a FF_ define1. Font style, Specified with a FS_ define2. Font size, Numeric value (only used for TTF fonts)3.

10/07/2002 01:19:24 AM 13

Page 18: Jpgraph Manual

For the builtin fonts the third, size, parameter is ignored since the size is fixed for the three builtin fonts. Theavailable font families and the corresponding name (in JpGraph 1.7) are listed in the table below.

Font family Type Note

FF_FONT0 Builtin font A very small font, only one style

FF_FONT1 Builtin font A medium sized font

FF_FONT2 Builtin font The largest bit mapped font

FF_ARIAL TTF font Arial font

FF_VERDANA TTF font Verdana font

FF_COURIER TTF font Fix pitched courier

FF_BOOK TTF font Bookman

FF_COMIC TTF font Comic sans

FF_HANDWRT TTF font Lucida handwriting

FF_TIMES TTF font Times New RomanPlease note that not all font families support all styles. The figure below illustrates each of the available fontfamilies and what styles you may use.

Figure 1: Illustration of all available fonts in JpGraph [src]

10/07/2002 01:19:24 AM 14

Page 19: Jpgraph Manual

We finally show some example of valid font specifications

$graph−>title−>SetFont(FF_FONT2);$graph−>title−>SetFont(FF_FONT2,FS_BOLD);$graph−>title−>SetFont(FF_ARIAL);$graph−>title−>SetFont(FF_ARIAL,FS_BOLD,24);

4.6.3 Adding additional fonts to JpGraph

Note: This information is only given here for very advanced users. No free support will ge given in the caseyou run into difficulties trying to add new fonts. At the moment adding new fonts require code modificationsas outlined below.

In order to add you favourite fonts there are three steps you need to follow :

Get the TTF file(s) and add it to your font directory. You need separate files for each of the styles youwant to support. These different files uses the following naming conventions:

Normal fonts file = [basename].ttf♦ Bold font file = [basename]"bd".ttf♦ Italic font file = [basename]"i".ttf♦ Bold Italic font file = [basename]"bi".ttf♦

1.

Define a new "FF_" constant naming your font family2. Update the Class TTF constructor in jpgraph.php with the mapping between your new constant andthe [basefilename]

3.

4.7 Specifying colors in JpGraph

Colors can be specified in three different ways

By using one of the, roughly, 400 pre−defined color names, e.g

SetColor("khaki");

1.

A named color can also be modified by adding a adjustment factor. An adjustment factor, 0 < f < 1, asmaller value will give a darker version and a value of 0 or 1 will return the original color. A value >1 will make the color brighter. A few examples

SetColor("khaki:0.5"); // A darker version of "khaki"SetColor("yellow:1.2"); // A slightly lighter version of "yellow"

By specifying a RGB triple, e.g.

SetColor(array(65,100,176));

2.

10/07/2002 01:19:24 AM 15

Page 20: Jpgraph Manual

By specifying the color as a hex string value

SetColor("#A16BFF");

3.

4.7.1 Available named colors

The chart below shows all available named colors.

10/07/2002 01:19:24 AM 16

Page 21: Jpgraph Manual

10/07/2002 01:19:24 AM 17

Page 22: Jpgraph Manual

10/07/2002 01:19:24 AM 18

Page 23: Jpgraph Manual

10/07/2002 01:19:24 AM 19

Page 24: Jpgraph Manual

10/07/2002 01:19:24 AM 20

Page 25: Jpgraph Manual

4.7.2 Theme colors for pie:s

For more on how to use the different themes see Working with 2D 3D pie plots

Theme 1: Earth

Theme 2: Pastel

10/07/2002 01:19:24 AM 21

Page 26: Jpgraph Manual

Theme 3: Water

Theme 4: Sand

10/07/2002 01:19:24 AM 22

Page 27: Jpgraph Manual

5 Understanding the JpGraph caching systemTo reduce load on the web server JpGraph implements an advanced caching system which avoids the burdenof always having to run the full image script.

Depending on the complexity of the image script (for example if it is doing several DB lookups) this couldsignificantly improve performance.

The rationale behind this is of course performance, and the observation that very few graphs are reallyreal−time, i.e. needs to be updated absolutely every time the graphing script is called.

5.1 Enabling the cache system

The enabling disabling of the cache system is controlled by two defines (in jpgraph.php)

DEFINE("USE_CACHE",true);DEFINE("READ_CACHE",true)

The first of these, USE_CACHE, is the master−switch which must be set to true to enable the caching system.The second switch READ_CACHE very seldom needs to be changed.

This second switch basically tells whether or not JpGraph should ever look in the cache. Setting this to falseand the master−switch to true would then always generate an new updated image file in the cache and thisnew image woudl be send back to the browser. The main use for this (admittedly) strange setting is if you liketo have the side effect of the script that a fresh image is always stored in the cache directory.

Once you have enabled the cache you must also make sure that a valid cache directory is setup. The cachedirectory is specified with the define

DEFINE("CACHE_DIR","/tmp/jpgraph_cache/");

You can of course change the default directory to whatever directory you fancy. But, you must remember oneimportant thing. The cache directory must be writable for the user running Apache/PHP.

5.2 Using the cache in your script

To use caching in your script you must supply a suitable file name which will be used to store the image in thecache. You can also supply a timeout value indicating how many minutes the cached image should beconsidered valid.

10/07/2002 01:19:24 AM 23

Page 28: Jpgraph Manual

These parameters are supplied in the initial Graph() method call which should be among the first in yourscript. Instead of manually specifying a file name to be used you could often use the special name "auto". Ifthe filename is specified as "auto" the cashed image will then be named the same as the image script but withthe correct extension depending on what image format have been chosen.

If you don't specify a file name no caching will be used no matter the settings of USE_CACHE (without a filename it is impossible!)

The following call to Graph() shows a typical use of the cache.

$graph = new Graph(300,200,"auto",60)

The above code will use the automatic filename and a make the cache valid for 60 minutes.

So, how does this all work now?

The first time you call your script (no cached image) everything will be as usual, the script will run and youwill in the end send back the image to the browser. However if you have the caching enabled JpGraph willautomatically have stored a copy of the generated image in the cache directory.

The next time you call the script the first thing that happens in the initial Graph() is that it will go and check inthe cache directory if the named image exists there. If this is the case it will also checks that the image isn'ttoo old (as compared to the specified timeout value). If the image is valid then the image will be streamedstraight back from the image file to the browser and the script will end it's execution.

Hence, if the image is found in the cache no code lines after the initial Graph() call will be executed

The design decision behind this is that your image script code never has to include anything special to makefull use of the cache. It will just automatically work.

5.3 Some final comments

If you want the timeout value to be "forever" then you can specify a 0 as the timeout value (or leavethe parameter blank). To regenerate the image you will have to remove the image file from the cache.This removal could for example be handled by a nightly cron−job

The cache system does not work together with client side image maps as is. (See• Using Client side image maps)• If you use images where you have enabled the anti−aliasing you should strongly consider usingcaching since anti−aliasing is quite time consuming compared to standard line drawings.

10/07/2002 01:19:24 AM 24

Page 29: Jpgraph Manual

6 Introducing X−Y plot type

6.1 Common feature for all graphs

This is a summary of the available feature for all Graph based charts.

6.1.1 Commonly used properties

Each graph can have three titles accessed through the properties 'Graph::title', ''Graph::subtitle' and''Graph::subsubtitle'

1.

Each graph have a legend accessed through the 'Graph::legend' property2. Each graph can have a left, center and right footer accessed through'Graph::footer::left','Graph::footer::center' and 'Graph::footer::right'

3.

You access the axis through 'Graph::xaxis', 'Graph::yaxis' and 'Graph::y2axis'4. You access the grids through 'Graph::xgrid', 'Graph::ygrid' and 'Graph::y2grid'5.

6.1.2 Commonly used methods

You add plot objects (barplots, pieplots, texts, bands, lines etc) with the 'Graph::Add() method.1. Each graph can have a specified margin set by 'Graph::SetMargin()'2. Each graph can have a fill color in the plot area 'Graph::SetColor()'3. The plot areas may have a box around it 'Graph::SetBox()'4. Each graph can have a specified margin color 'Graph::SetMarginColor()'5. Each graph can have a frame or not 'Graph::SetFrame()'6. Each graph can have a specified drop shadow 'Graph::SetShadow()'7. The grid lines can be either behind or in front of the plots 'Graph::SetGridDepth()'8. The plot can be rotated an arbitrary angle with 'Graph::SetAngle()'9. You can add a background image with 'Graph::SetBackgroundImage'10. You can change the overall apperance of the axis with 'Graph::SetAxisStyle'11.

6.2 Line plots

The first example draws a line graph consisting of 10 Y−values. In this first example we show the full code.In the following examples we will only show interesting piece of the code. The full code for the examplesshown below is always available by clicking the '[src]' link in the caption of the images below.

(File: example0.php)<?phpinclude ("../jpgraph.php");include ("../jpgraph_line.php");

// Some data$ydata = array(11,3,8,12,5,1,9,13,5,7);

// Create the graph. These two calls are always required

10/07/2002 01:19:24 AM 25

Page 30: Jpgraph Manual

$graph = new Graph(350,250,"auto"); $graph−>SetScale("textlin");

// Create the linear plot$lineplot=new LinePlot($ydata);$lineplot−>SetColor("blue");

// Add the plot to the graph$graph−>Add($lineplot);

// Display the graph$graph−>Stroke();?>

Figure 1: A simple line graph [src]

You might note a few things

Both the X and Y axis have been automatically scaled. We will later on show how you might controlthe autoscaling how it determines the number of ticks which is displayed.

By default the Y−grid is displayed in a "soft" color• By default the image is bordered and the margins are slightly gray.• By default the 0 label on the Y−axis is not displayed•

This is a perfect fine graph but looks a littel bit "sparse". To make it more interesting we might want to add afew things like

A title for the graph• Title for the axis• Increase the margins to account for the title of the axis•

From looking at the previous example you can see that you access all properties of JpGraph through theobjects you create. Graph(), LinePlot() and so on. In general all objects you can see in the graph is accessed

10/07/2002 01:19:24 AM 26

Page 31: Jpgraph Manual

through a named instance.

For example the title of the graph is accessed through the 'Graph::title' property. So to specify a title string youmake a call to the 'Set()' method on the title property as in:

$graph−>title−>Set('Example 2');

So by adding just a few more lines to the previous code we get a graph as shown below.

Figure 2: Same basic graph as in previous figure but with a titles for graph and axis. [src]

To achieve this we just needed to add a few more lines. (We only show the part of example 1 we changed, tolooka t the full source just click the [src] link in the caption. )

// Setup margin and titles$graph−>img−>SetMargin(40,20,20,40);$graph−>title−>Set("Example 2");$graph−>xaxis−>title−>Set("X−title");$graph−>yaxis−>title−>Set("Y−title");

Again there are a couple of things you should note here

A default font and size is used for the text• The default position for the title of the graph is to be centered at the top• The default position for the title of the x−axis is the far right and for the y−axis centered and rotatedin a 900 angle.

A nice change would now be to have all the titles in a bold font and the line plot a little bit thicker and in bluecolor. Let's do that by adding the lines

10/07/2002 01:19:24 AM 27

Page 32: Jpgraph Manual

$graph−>title−>SetFont(FF_FONT1,FS_BOLD);$graph−>yaxis−>title−>SetFont(FF_FONT1,FS_BOLD);$graph−>xaxis−>title−>SetFont(FF_FONT1,FS_BOLD);$lineplot−>SetColor("blue");$lineplot−>SetWeight(2); // Two pixel wide

Again please note the consistent interface. To change font you just have to invoke the SetFont() method on theappropriate object. This principle is true for most methods you will learn. The methods may be applied to avariety of objects in JpGraph. So for example it might not come as a big surprise that to have the Y−axis inred you have to say:

$graph−>yaxis−>SetColor("red")

or perhaps we also want to make the Y−axis a bit wider by

$graph−>yaxis−>SetWidth(2)

As a final touch let's add a frame and a drop shadow around the image since this is by default turned off. Thisis done with

$graph−>SetShadow()

The result of all these modifications are shown below.

Figure 3: Making the image a little bit more interesting by adding som colors and changing the fonts [src]

6.2.1 Adding plot marks to line−plots XXX

It might sometimes be desirable to highlight the data−points with marks in the intersection between the givenx and Y−coordinates. This is accomplished by specifying the wanted plot mark type for the "mark" propertyof the line graph. A full list of all available marks is given in the class reference PlotMarks

10/07/2002 01:19:24 AM 28

Page 33: Jpgraph Manual

For now let's just add a triangle shape marker to our previous graph by adding the line

$lineplot−>mark−>SetType(MARK_UTRIANGLE);

Thiw will give the graph as shown below

Figure 4: Adding markers to the previous example [src]

If you like you can ofd course both change the size, fill−color and frame color of the choosen plot mark.

The colors of the marks will, if you don't specify them explicitly, follow the line color. Please note that if youwant different colors for the marks and the line the call to SetColor() for the marks must be done after the callto the line since the marks color will always be reset to the lines color when you set the line.

6.2.2 Displaying the values for each data point

As a final easy modification we can enable the display of the data value above each data point. The value isrepresented by the 'value' property in the plot. (You can read more about the possibilities of the display valuein the class reference.)

To enable the display of the value you just need to call the Show() method of the value as in

$lineplot−>value−>Show()

Adding that line to the previous line plot would give the result shown below.

10/07/2002 01:19:24 AM 29

Page 34: Jpgraph Manual

Figure 5: Displaying the value for each data point [src]

We can of course change both color, font and format of the displyed value. So for example if we wanted thedisplay values to be dark red, use a bold font and have a '$' in front we need to add the lines

$lineplot−>value−>SetColor("darkred");$lineplot−>value−>SetFont(FF_FONT1,FS_BOLD);$lineplot−>value−>SetFormat("$ %0.1f");

This would then result in the following image

Figure 6: Making the display values a little bit more interesting [src]

Sidebar: You can achieve more advanced formatting by using not just the printf() style format string by a format callback function. This could allow you tochange the displayed value with more advanced formatting such as displaying money values with "," to spearte thousends.

6.2.3 Adding several plots to the same graph

What if we want to add a second plot to the graph we just produced? Well, this is quite straightforward andjust requires two simple step:

Create the second plot1. Add it to the gaph2.

10/07/2002 01:19:24 AM 30

Page 35: Jpgraph Manual

To create the second plot we need some data (we could of course use the same data as for the first plot butthen we wouldn't be able to see the new plot!)

The following lines show how to create the new plot and add it to the graph (we only show the new lines − notthe full script)

$ydata2 = array(1,19,15,7,22,14,5,9,21,13);$lineplot2=new LinePlot($ydata2);$lineplot2−>SetColor("orange");$lineplot2−>SetWeight(2);

$graph−>Add($lineplot2);

Making these changes to the previous graph script would generate a new graph as illustrated below.

Figure 7: Adding a second plot to the previous graph [src]

There is a few things worth noting here

The Y−scale has changed to accommodate the larger range of Y−values for the second graph.• If you add several plots to the same graph they should contain the same number of data points. This isnot a requirement (the graph will be automatically scaled to accommodate the plot with the largestnumber of points) but it will not look very good since one of the plot end in the middle of the graph.

6.2.4 Adding a second Y−scale

As you saw in the preceding example you could add multiple plots to the same graph and Y−axis. Howeverwhat if the two plots you want to display in the graph has very different ranges. One might for example haveY−values like above but the other might have Y−values in the 100:s. Even though it is perfectly possible toadd them as above the graph with the smallest values will have a very low dynamic range since the scale mustaccomplish the bigger dynamic range of the second plot.

The solution to this is to use a second Y−axis with a different scale and add the second plot to this Y−axisinstead. Let's take a look at how that is accomplished.

10/07/2002 01:19:24 AM 31

Page 36: Jpgraph Manual

First we need to create a new data array with large values and secondly we need to specify a scale for the Y2axis. This is done by the lines

$y2data = array(354,200,265,99,111,91,198,225,293,251);$graph−>SetY2Scale("lin");

and finally we create a new line plot and add that to the second Y−axis. Note that we here use a new method,AddY2(), since we want this plot to be added to the second Y−axis. Note that JpGraph will only support twodifferent Y−axis. This is not considered a limitation since using more than two scales in the same graph wouldmake it very difficult to interpret the meaning of the graph.

To make the graph a little bit more aesthetical pleasing we use different colors for the different plots and letthe two different Y−axis get the same colors as the plots.

The resulting graph is shown below. source)

Figure 8: Adding a second Y−scale plot to the same graph [src]

6.2.5 Adding a legend to the graph

With more than one plot on the same graph it is necessary to somehow indicate which plot is which. This isnoramlly done by adding a legend to the graph.

You will see that each plot type has a 'SetLegend()' method which is used to name that plot in the legend. SOto name the two plots in the example we have been working with so far we need to add the lines

$lineplot−>SetLegend("Plot 1");$lineplot2−>SetLegend("Plot 2");

to the previous code. The resulting graph is shown below

10/07/2002 01:19:24 AM 32

Page 37: Jpgraph Manual

Figure 9: Adding a legend to the graph [src]

As you can see the legend gets automatically sized depending on how many plots there are that have legendtexts to display. By default it is placed with it's top right corner close to the upper right edge of the image.Depending on the image you might want to adjust this or you might want to add a larger margin which is bigenough to accompany the legend. Let's do both.

First we increase the right margin and then we place the legend so that it is roughly centred. We will alsoenlarge the overall image so the plot area doesn't get too squeezed.

To modify the legend you access the 'legend' property of the graph. For a full reference on all the possibilities(changing colors, layout, etc) see class legend in the class reference

For this we use the legends 'SetPos()' method as in

$graph−>legend−>Pos(0.05,0.5,"right","center");

Doing this small modification will give the result shown below

Figure 10: Adjusting the layout to give more rooms for the legend [src]

The above method 'SetPos()' deserves some explanation since it might not be obvious. You specify theposition as a fraction of the overall width and height of the entire image. This makes it possible for you toresize the image within disturbing the relative position of the legend. We will later see that the same method is

10/07/2002 01:19:24 AM 33

Page 38: Jpgraph Manual

just to place arbitrary text in the image.

To give added flexibility one must also specify to what edge of the legend the position given should berelative to. In the example above we have specified "right" edge on the legend for the for the horizontalpositioning and "center" for the vertical position.

This means that the right edge of the legend should be position 5 % of the image width from the right. If youhad specified "left" the the legends left edge would be positioned 5 % of hte image width from the image leftside.

By default the legends in the legend box gets stacked on top of each other. The other possibility is to havethem sideways. To adjust this you use the SetLayout() method. Using a horizontal layout with the previousexample give the following result.

Figure 11: Using a horizontal layout for the legends [src]

6.2.6 Handling null−values in lineplots

JpGraph offers two ways of handling null values (or discontinuties) in the data. You can either have a "whole"in the data or the line may be extended between the previous and next data point in the graph.

If the data value is null ("") or the special value "x" then the data point will not be plotted and will leave a gapin the line.

If the data value is "−" then the line will be drawn between the previous and next point in the data ignoring the"−" point.

The following example shows both these posibilities.

10/07/2002 01:19:24 AM 34

Page 39: Jpgraph Manual

Figure 12: Handling null values in line graphs [src]

6.2.7 Using the step−style to render line plots

Step style refers to an alternate way of rendering line plots by not drawing a direct line between two adjacentpoints but rather draw two segements. The first segment being a horizontal line to the next X−value and then avertical line from that point to the correct Y−value. This is perhaps easier demonstrated by an example as seenbelow.

You specify that you want the plot to ber rendered with this style by calling the method SetStepStyle() on thelineplot.

Figure 13: Rendering a line plot with the step style [src]

6.2.8 Using logarithmic scale

Using a logarithmic scale requires you to include the logarithmic add on module in "jpgraph_log.php". So youmust have the line

10/07/2002 01:19:24 AM 35

Page 40: Jpgraph Manual

include("jpgraph_log.php");

on the top of your code. To Illustrate how to use a logarithmic scale let's make the right Y scale in theprevious example a logarithmic scale. This is done by the line

$graph−>SetY2Scale("log");

This will then give the following result

Figure 14: Using a logarithmic scale for both the Y2 axis [src]

You can of course also use a logarithmic X−scale as well. The following example shows this.

Figure 15: Example of using log scale on both X and Y axis together with a linear Y2 scale [src]

Even though we have so far only shown line graphs logarithmic scale can also be used for bar, error, scatterplots as well. Even radar plots supports the use of logarithmic plots. The following example shows how to usea logarithmic scale for a bar graph.

10/07/2002 01:19:24 AM 36

Page 41: Jpgraph Manual

Figure 16: Example of using logarithmic scale togther with bar plots [src]

6.2.9 More on scales

As you saw in the previous example it is possible to use different types of scales. In JpGraph you can use thefollowing scales

Linear scale, the standard "scale"• Logarithmic scale• Integer scale, very similair to linear scale but restricts the scale values (and labels) to integer values.• Text scale, Similair to integer scale and used when only the numbering of items is relevant. A textscale is almost exclusivly used for the X−axis. A typical example for this is the X−axis for a bar plot.The labels for the text scale is ususally replaced by user supplied texts. Text scales can only be usedfor the X−axis (it doesn't make sense for the Y−scale).

Any combination of these may be used. Linear and logarithmic scales are pretty straightforward. The textscale might deserve some explanation. The easiest way to think of the text scale is as a linear scale consistingof only natural numbers, i.e. 0,1,2,3,4,... . This scale is used when you just have a number of Y−values youwant to plot in a consecutive order and don't care about the X−values. For the above example it will also workfine to use a linear X−scale (try it!). However, the scale is now treated as consisting or real numbers so theautoscaling, depending on the size of the image an the number of data points, might decide to display otherlabels then the natural numbers., i.e. a label might be 2.5 say. This is not going to happen if you use a textscale.

The normal practice for text scale is to specify text strings as labels instead as the default natural numbers.You can specify text strings for the labels by calling the SetTickLabels() method on the Axis.

To specify the scale you use the SetScale() method. A few examples might help clarify this.

"textlin", text−scale for X−axis, Linear scale for Y−axis• "linlin", linear−scale for X−axis, Linear scale for Y−axis• "linlog", linear−scale for X−axis, Logarithmic scale for Y−axi• "loglog", Logarithmic scale for X−axis, Logarithmic scale for Y−axis•

10/07/2002 01:19:24 AM 37

Page 42: Jpgraph Manual

"textlog", Text scale for X−axis, Logarithmic scale for Y−axis•

As you can see all your graphs will require at least one call to SetScale() in the beginning of your script.Normally it will come right after the creation of the Graph().

To specify the scale for the Y2 axis you use the SetY2Scale() Since you only specify one axis you onlyspecify "half" of the string in the previous examples. So to set a logarithmic Y2 scale you will call

$graph−>SetY2Scale("log");

6.2.10 Adjusting the gridlines in the plot

By default only the Y−axis have grid lines and then only on major ticks, i.e. ticks which have a label. It is ofcourse possible to change this. Both the X , Y and Y2 can have grid lines. It is also possible to let the gridlinesalso be drawn on the minor tick marks, i.e. ticks without a label. Lets see how we can apply this to the graphabove.

The grid is modified by accessing the xgrid (or ygrid) component of the graph. So to disply minor grid linesfor the Y graph we make the call

$graph−>ygrid−>Show(true,true)

The first parameter determines if the grid should be displayed at all and the second parameter determineswhether or not the minor grid lines should be displayed.

If you also wanted the gridlines to be displayed for the Y2 axis you would call

$graph−>y2grid−>Show(true,true)

Note. In general it is not a good idea to display both the Y and Y2 gridlines since the resulting image becomesdifficult to read for a viewer.

We can also enable the X−gridlines with the call

$graph−>xgrid−>Show(true)

In the above line we will of course only just enable the major grid lines.

To bring all this together we will display a graph with gridlines for both Y and X axis enabled.

10/07/2002 01:19:24 AM 38

Page 43: Jpgraph Manual

Figure 17: Enabling major and minor gridlines for Y−axis and major grid lines for the X−axis [src]

Note: If you think the first value of the Y−axis is to close to the first label of the X−axis you have the optionof either increasing the margin (with a call to SetLabelMargin() ) or to hide the first label (with a call toHideFirstTickLabel() )

6.2.11 Specifying text labels for the X−axis

You might want to have specific labels you want to use for the X−axis when this has been specified as a "text"scale. In the previous example each Y−point might represent a specific measurement for each of the first 10month. We might then want to display the name of the months as X−scale.

To specify the labels on the scale you make use of the SetTickLabels() method.

To get a localized version of the name of the month you can use a nice feature in JpGraph, the global'$gDateLocal' object which is an instance of the DateLocale

This class has a number of methods to get localized versions of relevant names for dates, (months andweekdays).

So to specify the X−axis with the short form of the month names we use the construction

$a = $gDateLocale−>GetShortMonth();$graph−>xaxis−>SetTickLabels($a);

This will, now result in the image displayed below

10/07/2002 01:19:24 AM 39

Page 44: Jpgraph Manual

Figure 18: Specifying text labels for the X−axis [src]

Note: It is also perfectly legal to override the default labels for the Y (and Y2) axis in the same way, howeverthere is seldom need for that. Please note that the supplied labels will be applied to each major tick label. Ifthere are insufficient number of supplied labels the non−existent positions will have empty labels.

6.2.12 Adjusting the ticks on a text scale

As can be seen in the previous example the X−axis is slightly cluttered with the labels very close to eachother. We might rectify this by either enlarging the image or just displaying fewer tick label on the x−axis.

Specifying that we only want, for example, to print every second label on the axis is done by a call to themethod SetTextLabelInterval() Which would result in the graph

Figure 19: Just printing every second label on the X−axis [src]

If the text labels are long (for example full dates) then another way might bne to adjust the angle of the text.We could for example choose to rotate the labels on the X−axis by 90 degrees. With the help of theSetLabelAngle()

Which would then result in the image below

10/07/2002 01:19:24 AM 40

Page 45: Jpgraph Manual

Figure 20: Rotating the X−labels 90 degrees [src]

Note: The internal fonts which we have been using so only supports 0 or 90 degrees rotation. To use arbitraryangles you must specify TTF fonts. More on fonts later.

6.2.13 Using filled line graphs

Using a filled line plot is not much different from using a normal line plot, in fact the only difference is thatyou must call the method SetFillColor() on a normal line plot. This will then fill the area under the line graphwith the chosen color.

In the example below we have also, as an example, specified plot marks (see previous sections).

Figure 21: Filled line graph with plot marks [src]

Note 1. If you add multiple filled line plots to one graph make sure you add the one with the highest Y−valuesfirst since it will otherwise overwrite the other plots and they will not be visible. Plots are stroked in the orderthey are added to the graph, so the graph you want front−most must be added last.

Note 2. When using legends with filled line plot the legend will show the fill color and not the bounding linecolor.

Note 3. Filled line plots is only supposed to be used with positive values. Filling line plots which havenegative data values will probably not have the apperance you expect.

10/07/2002 01:19:24 AM 41

Page 46: Jpgraph Manual

As you can see from the graph above the gridlines are below the filled line graph. If you want the gridlines infront of the graph you can adjust the depth with call to Graph::SetGridDepth() As the following exampleshows

Figure 22: Adjusting the depth of the gridlines [src]

6.2.14 Using accumulated line graphs

Accumulated line graphs are line graphs that are "stacked" on top of each other. That is, the values in thesupplied data for the Y−axis is not the absolute value but rather the relative value from graph below. Forexample if you have two line graphs with three points each, say [3,7,5] and [6,9,7]. The first graph will beplotted on the absolute Y−values [3,7,5] the second plot will be plotted at [3+6, 7+9, 5+7], hence the values ofthe previous graphs will be used as offsets.

You may add any number of ordinary line graphs together. If you want to use three line plots in anaccumulated line plot graph you write the following code

// First create the individual plots$p1 = new LinePlot($datay_1);$p2 = new LinePlot($datay_2);$p3 = new LinePlot($datay_3);

// Then add them together to form a accumulated plot$ap = new AccLinePlot(array($p1,$p2,$p3));

// Add the accumulated line plot to the graph$graph−>Add($ap);

You might of course also fill each line plot by adding the lines

$p1−>SetFillColor("red");$p2−>SetFillColor("blue");

10/07/2002 01:19:24 AM 42

Page 47: Jpgraph Manual

$p3−>SetFillColor("green");

Using some appropriate data this might then give a graph perhaps like the one showed in the figure below

Figure 23: Accumulated filled line graph [src]

6.3 Bar graphs

Jpgraph also supports 2D vertical bar plots. Before you can use any bar plots you must make sure that youincluded the file "jpgraph_bar.php" in your script.

Using bar plots is quite straightforward and works in much the same way as line plots which you are alreadyfamiliar with from the previous examples. Assuming you have a data array consisting of the values[12,8,19,3,10,5] and you want to display them as a bar plot. This is the simplest way to do this:

$datay=array(12,8,19,3,10,5);$bplot = new BarPlot($datay);$graph−>Add($bplot);

If you comapre this to the previous line examples you can see that the only change necessary was that insteadof createing a new line plot (via the new LinePlot(...) call) we used the statement new BarPplot().

The other change we should do is to make sure the X−axis have an text−scale (it is perfectly fine to use alinear X−scale but in most cases this is not the effect you want when you use a bar graph, see more below).With this two simple change we will now get a bar graph as displayed in the following image

10/07/2002 01:19:24 AM 43

Page 48: Jpgraph Manual

Figure 1: A very simple bar graph [src]

You can of course modify the apperance of the bar graph. So for example to change the fill color you woulduse the BarPlot::SetFillColor() method. MAking this small change to the previous example would give theexpected effect as can be seen in the next example.

Figure 2: A very simple bar graph with changed fill color [src]

Sidebar: You should note from the previous two graphs that slight change in apperance for the X−scale. Thebar graphs gets automatically centered between the tick marks when using as text x−scale. If you were to usea linear scale they would instead start at the left edge of the X−axis and the X−axis would be labeled with alinear scale. As is illustrated in the (small) example below

Figure 3: A small example with a bar graph using a linear X−scale [src]

6.3.1 Adjusting the width of the bars

JpGraph allows you to easy customize the apperance of the bar graph, for example to change the width ofeach bar. The width of each bar can be specified either as a fraction of the width between each major tick or as

10/07/2002 01:19:24 AM 44

Page 49: Jpgraph Manual

an absolute width (in pixels).

To set the width in fraction you use the method SetWidth() and to set the width in pixels you use theSetAbsWidth()

As an example let's take the previous example and set the width to 100% of the distance between the ticks.The example will now become

Figure 4: Setting the width of the bars to 100% of the tick width [src]

6.3.2 Displaying the value of each bar

You can easily choose to display the value (and it's format) on top of each bar by accessing the bar's 'value'property. So for example by just adding the line

$barplot−>value−>Show();

Will enable the values in it's simplest form and will give the result

Figure 5: Showing the values for each bar [src]

You cane see a small nuiance in this graph. The autoscaling algorithm chooses quite tight limits for the scaleso that the bars just fit. Adding the value on top of the bar makes it collide with the top of the graph. To

10/07/2002 01:19:24 AM 45

Page 50: Jpgraph Manual

remedy this we tell the autoscaling algorithm to allow for more "grace" space at the top of the scale by usingthe method SetGrace() which is used to tell the scale to add a percentage (of the total scale span) more spaceto either one end or both ends of the scale. In this case we add 20% more space at the top to make more roomfor the values with the line

$graph−>yaxis−>scale−>SetGrace(20);

This will then give the graph as shown below

Figure 6: Adding some grace space to the top of the Y−scale [src]

You can also adjust the general position of the value in respect to the bar by using the BarPlot::SetValuePos()method. You can set the position to either 'top' (the default) , 'center' or 'bottom'. The graph below shows thevalue being positioned in the center. In this example we have also adjusted the format to just display the valueas an integer without any decimals.

Figure 7: Putting the values in the middle of the bar. [src]

It is also possible to specify a more fine grained control on how you want the values presented. You can forexample, rotate them, change font, change color. It is also possible to adjust the actual value displayed byeither using a printf()−type format string or with the more advanced technique of a format callback routine.

To show what you can do we just give another example for you to examine without much further

10/07/2002 01:19:24 AM 46

Page 51: Jpgraph Manual

explanations. Just remember that to have text at an angle other than 0 or 90 degrees we have to use TTF fonts.Even though we haven't explained the SetFont() method it should be fairly obvious.

Figure 8: Making the displayed values more interesting [src]

6.3.3 Adding a drop shadow to the bar

One simple way of making the bar graph more attracting is to add a drop shadow to each bar. This is done bycalling the SetShadow() method. An example will clarify this.

Figure 9: Adding a drop shadow to each bar [src]

6.3.4 Adjusting the alignment of bars ona text scale

As you have seen from the previous examples bar graphs are normally centered between the trick marks on atext scale. However, you can modify this behavious by calling the method BarPlot::SetAlign()

6.3.5 Using grouped bar plots

These types of bar graph is used to easy group two or more bars together around each tick (X−value). Thebars will be placed immediately beside each other and as a group centred on each tick mark. A grouped bar iscreated by aggregating two or more ordinary bar graphs and creating a GroupBarPlot() From two ordinary bargraphs along the lines of

10/07/2002 01:19:24 AM 47

Page 52: Jpgraph Manual

// Create the bar plots$b1plot = new BarPlot($data1y);$b1plot−>SetFillColor("orange");

$b2plot = new BarPlot($data2y);$b2plot−>SetFillColor("blue");

// Create the grouped bar plot$gbplot = new GroupBarPlot(array($b1plot,$b2plot));

// ...and add it to the graPH$graph−>Add($gbplot);

The following example illustrates this type of graph

Figure 10: A grouped bar plot [src]

There is no limit on the number of plots you may group together.

If you use the SetWidth() method on the GroupBarPlot() this will affect the total width used by all the addedplots. Each individual bar width will be the same for all added bars. The default width for grouped bar is 70%.

Setting the grouped with to 0.9 would result in the image below.

10/07/2002 01:19:24 AM 48

Page 53: Jpgraph Manual

Figure 11: Adjusting the width for a gropued bar plot. [src]

6.3.6 Using accumulated bar plots

The final varietys of group bars you can have are accumulated bars. They work in much the same way asaccumulated line plots described above. Each plot is stacked on top of each other.

You create accumulated bar plots in the same way as grouped bar plots by first creating a number of ordinarybar plots that are then aggregated with a call to AccBarPlot();

An example makes this clear. Let's use the same data as in the two examples above but instead of grouping thebars we accumulate (or stack) them. The code would be very similar (actually only one line has to change)

Figure 12: Accumulated bar plots [src]

6.3.7 Using grouped accumulated bar graphs

It is perfectly possible to combine the previous bar types to have grouped accumulated bar plots. This is doneby just adding the different accumulated plots to a group bar plot, for example the following code would dothat.

// Create all the 4 bar plots$b1plot = new BarPlot($data1y);$b1plot−>SetFillColor("orange");$b2plot = new BarPlot($data2y);$b2plot−>SetFillColor("blue");$b3plot = new BarPlot($data3y);$b3plot−>SetFillColor("green");$b4plot = new BarPlot($data4y);$b4plot−>SetFillColor("brown");

// Create the accumulated bar plots$ab1plot = new AccBarPlot(array($b1plot,$b2plot));$ab2plot = new AccBarPlot(array($b3plot,$b4plot));

10/07/2002 01:19:24 AM 49

Page 54: Jpgraph Manual

// Create the grouped bar plot$gbplot = new GroupBarPlot(array($ab1plot,$ab2plot));

// ...and add it to the graph$graph−>Add($gbplot);

Putting this together in an example would then produce the graph as whown below

Figure 13: Combining grouped and accumulated bar plots [src]

6.3.8 Horizontal bar graphs

It can often come in handy to have horizontal bar graphs especially if you have a large number of values todisplay. Even though JpGraph doesn't directly support horizontal bar graphs this is easy achived byconstructing a normal vertical bar graph which is then rotated 90 degrees.

The example below shows a simple example of this

10/07/2002 01:19:24 AM 50

Page 55: Jpgraph Manual

Figure 14: A typical horizontal bar graph with the Y−axis at the bottom [src]

In order to achieve this effect you should study the above example carefully and you might notice two things

We dont simply rotate the graph we also specify that we want the rotation center to be the middle ofthe entire image. The reason for this is that by default (See the section on rotating plots) the pivotpoint for rotation is the center of the plotarea. Since the center of the plotarea is not necessary thecenter of the entire image the rotation might be a little bit difficult to predict since it will depend onthe margins specified. <

The size of the plotarea is determined from the original width and height of the image taking thespecified margin into account. When the the plotartea is rotated 90 degrees clockwise what was theleft margin now in effect becomw the upper margin and so on. This is a small nuance since weconceptually want to specify the margins directly in the rotated plot.I have choosen not to add any special margin method specifically for a 90 degree rotated plot. Sinceto compensate for this since is fairly easy once you understood this problem.For this reason theexample code let's you specify the percived margins and they are then backwards converted to theirhorizontal equivalent. If the width and height differs we must also take that into account.The code below extracts the lines that makes this simple conversion

// Since we swap width for height (since we rotate it 90 degrees)// we have to adjust the margin to take into account for that

10/07/2002 01:19:24 AM 51

Page 56: Jpgraph Manual

$top = 50;$bottom = 30;$left = 50;$right = 20;$adj = ($height−$width)/2;$graph−>SetMargin($top−$adj,$bottom−$adj,$right+$adj,$left+$adj);

We finally show three more examples of horizontal bar plots. In the first plot we have hidden the Y−axus andin the second we have positioned the Y − axis at top as opposed to the bottom as the first example shows.

Figure 15: Horizontal bar graph with hidden Y axis [src]

10/07/2002 01:19:24 AM 52

Page 57: Jpgraph Manual

Figure 16: Horizontal bar graph with Y axis at the top [src]

In the final example which is almost similair to the two first we illustrate the use of labels with more than oneline.

10/07/2002 01:19:24 AM 53

Page 58: Jpgraph Manual

Figure 17: Horizontal bar graph with manual integer scale as well as multiple line labels [src]

6.3.9 Using gradient fill for bar graphs

It is possible to use color gradient fill for the individual bars in the bar graph.

Color gradient fill fills a rectangle with a smooth transition between two colors. In what direction thetransition goes (from left to right, down and up, fomr the middle and out etc) is determined by the style of thegradient fill. JpGraph currently supports 7 different styles. All supported styles are displayed in the figurebelow.

10/07/2002 01:19:24 AM 54

Page 59: Jpgraph Manual

Figure 18: [src] Figure 19: [src] Figure 20: [src]

Figure 21: [src] Figure 22: [src] Figure 23: [src]

Figure 24: [src]

To specify a gradient fill for the bar plots you make use of the method BarPlot::SetFillGradient() . See theclass reference for details of this function.

When using gadient fills there are a couple of caveats you should be aware of:

gradient filling is computational expensive. Large plots with gradient fill will take in the order of 6times longer to fill then for a normal one−color fill. This might to some extent be helped by makinguse of the cache feature of JpGraph so that the graph is only generated a few times.

gradient filling will make use of much more colors (by definition) this will make the color palette forthe image bigger and hence make the overall image larger. It might also have some severe effect onusing anti−aliased line in the same image as color gradient filling since anti−aliased lines also havethe possibility to make use of many colors. Hence the color palette might not be big enough for all thecolors you need. So if you use gadient fills you should also be using a true−color image since youotherwise run out of colors.This problem is often seen as that for no apperant reason some color you have specified in the imagedoes appear as another color. (This is not a bug in JpGraph!) This is something to especially watchout for when enabling anti−alising since that also uses a lot of colors. Since the numbers of colorsused with anti−alising depends on the angle on the lines it is impossible to foresee the number ofcolors used for this.

6.3.10 Creating semi−filled bar graphs

Semi filled bar graphs are in principle the same as normal filled bar graphs but with the additional feature thatyou can choose to only fill a specified range (or ranges) of X−coordinates. The figure below illustrates this

10/07/2002 01:19:24 AM 55

Page 60: Jpgraph Manual

Figure 25: Semi−filled line graph [src]

I this example we defined two areas along the X−axis to be filled. You can add filled areas by using themethod AddArea() and specifying range and color for the filled area.

6.4 Error plots

Error plots are used to visually indicate uncertainty in data points. This is done by for each X value by givingboth a minimum and a maximum Y−value.

Before you can use error plots you must remember to include the file "jpgraph_error.php" in your script.

The following example illustrates a simple error bar. We will have 5 points, so we need 10 Y−values. We alsowould like the error bars to be red and 2 pixels wide. All this is accomplished by creating an ErrorPlot() inmuch the same way as, for example, a normal line plot. Doing this would now give the example shown below.

Figure 1: A simple error bar [src]

You might notice that there is one displeasing aesthetical quality of this graph. The X−scale is just wide

10/07/2002 01:19:24 AM 56

Page 61: Jpgraph Manual

enough to just accompany the number of error bars and hence the first bar is drawn on the Y−axis and the andlast bar just at the edge of the plot area. To adjust this you might call the SetCenter() method which will adjustthe X−scale so it does not use the full width of the X−axis.

The following example illustrates the use of this feature by applying this technique to the previous example

Figure 2: Adjusting the X−scale not to use the full width of the X−axis. [src]

6.4.1 Using line error plots

A line error plot is an error plot with the addition that a line is drawn between the average value of each errorpair. You use this type of plot the exact same way you would use an error plot. The only change is that youmust instantiated an ErrorLinePlot() instead and make sure you have included the "jpgraph_line.php" sincethe line error plot makes use of the line plot class to stroke the line.

To control the various properties of the line drawn the "line" property of the error line plot may be accessed.So, for example, if you want the line to be 2 pixels wide and blue you would have to add the following twolines

$elplot−>line−>SetWeight(2);$elplot−>line−>SetColor("blue");

to generate the graph as shown below

10/07/2002 01:19:24 AM 57

Page 62: Jpgraph Manual

Figure 3: Linear error plot [src]

You may of course add legends to none, one or both of the line types in the above graph. So for example if wewanted the legend "Min/Max" for the red error bars and a legend "Average" for the blue line you would haveto add the lines

$errplot−>SetLegend("Min/Max");$errplot−>line−>SetLegend("Average");

The resulting graph will now look like (note that we are using the default placement of the legend box)

Figure 4: Addding a legend box to the line error plot. [src]

6.5 Scatter plots

Scatter plots are very simple; they plot a number of points specified by their X− and Y−coordinate. Each pointis stroked on the image with a mark as with lineplots. The stroked marks can also be connected with anoptional line.

Sidenote: Even though it is only scatter plot that was designed to be used with X,Y plots it is perfectly possible to use use both X,Y coordinates for bar andline plots as well.

Even though you would normally supply X−coordinates it is still perfectly possible to use a text−scale forX−coordinates to just enumerate the points. This is especially usefull when using the "Impuls" type of scatter

10/07/2002 01:19:24 AM 58

Page 63: Jpgraph Manual

plot as is shown below.

Scatter pots are created by including the jpgraph extension "jpgraph_scatter.php" and then creating aninstance of plot type of ScatterPlot(). To specify the mark you want to use you access the mark with theinstance variable "mark" in the scatter plot. The default is to use an unfilled small circle.

To create a scatter plot you will create an instance

A simple example using just default values will illustrate this

Figure 1: The simplest possible scatter plot [src]

We can easily adjust the size and colors fo the markers to get another effect as shown below

Figure 2: The simplest possible scatter plot with adjusted marks [src]

Another possible vaiant of scatter plot is impuls−scatter plots. This is a variant of normal scatter plot whereeach mark have a line from the mark to the Y=0 base line. To change a scatter plot into an impuls scatter plotyou have to call the method SetImpuls() on the scatter plot.

This type of plots are often used to illustrate signals in conjunction with digital signal processing. Thefollowing two examples illustrates simple use of impuls plots.

10/07/2002 01:19:24 AM 59

Page 64: Jpgraph Manual

Figure 3: A simple impuls plot [src]

The next example shows how to modify the color and width of the impuls plot

Figure 4: A modified impuls plot [src]

Sidebar: You may draw impuls graphs without any mark by specifying the mark type as (−1) . That way only the impuls lines will be drawn.

As a final touch we show two more advanced impuls graphs . In these graphs we have used more advancedformatting for the Y−axis labels as well as adjusted the position of the axis position.

Figure 5: In this imuplsplot we have adjusted the position of the X−axis to the bottom and also added more decimals to the labels on the Y−axis [src]

10/07/2002 01:19:24 AM 60

Page 65: Jpgraph Manual

Figure 6: In this impuls plot we have also added a lineplot with a dotted line style. [src]

6.6 Combining different graph types

It is perfectly legal to add several different plot types to the same graph. It is therefore possible to mix lineplots with (for example) filled bar graphs. What you should keep in mind doing this is the order in whichthese plots are stroked to the image since a later stroke will overwrite a previous one. All plots are stroked inthe order you add them, i.e. the first plot added will be stroked first. You can therefore control which plot isplaced in the background and which one is placed in the foreground by the order you add them to the plot.

To start simple we just mix a filled line plot with a non−filled line plot as the following example shows.

Figure 1: Mixing filled and non−filled line plots in the same graph [src]

Let's now go to something a little bit more complicated. How to mix bar and line graphs. Let's just take one ofour previous bar graphs and add a line plot to it and see what happens.

10/07/2002 01:19:24 AM 61

Page 66: Jpgraph Manual

Figure 2: Adding a line to a bar graph [src]

Not too bad. But we can't see the line so we change the order in which we add the lines to the graph and seeswhat happens.

Figure 3: Adding a line to a bar graph, in different orderv2 [src]

If you want the line points to be aligned in the center of the bars you can accomplish this is two ways.

If you use a text scale then you need to call the LinePlot::SetBarCenter()

Figure 4: Centering the line point in the middle of the bars using LinePlot::SetBarCenter() [src]

10/07/2002 01:19:24 AM 62

Page 67: Jpgraph Manual

You can also use an integer scale. This places both the bar and the line points centered at the tick marks. Asthe following example will show

Figure 5: Using a linear scale [src]

Note: In this example we also have illustrated the fact that you can add text labels to a linear (or integer)scales as well.

As a final example we show how you can combine a scatter plot and a line plot which could be used toillustrate a regression line fitting.

Figure 6: Combining a scatter plot and a line plot [src]

6.7 Specifying the scale manually

Normally the automatic scaling should be doing an adequate job in most circumstances but there might becases where you like to manually set the scale. For example if you have several graphs where you like to beable to easlily compare them and therefore want them all to have the same scale.

To specify a manual scale you have to add arguments to the standard Graph::SetScale() method. So to specifythat you want an Y−scale between 0 and 100 you need to write

$graph−>SetScale("textlin",0,100);

10/07/2002 01:19:24 AM 63

Page 68: Jpgraph Manual

When you specify a scale manually there is one additional thing you need to decide. How the tick marksshould be positioned. You have two choices

Manually specify the tick marks with a call to LinearTicks::Set() This is the default behavious. Henceevery manually specified scale must be followed by a call that sets the tick marks. For example

$graph−>SetScale("textlin",0,100);$graph−>yscale−>ticks−>Set(10,5);

1.

Will set the major tick marks every at 0,10,20,.. And every minor tick mark in between(0,5,10,15,20,25,...).

Let JpGraph decide the best tick marks. You have to tell JpGraph that you want the tick marks to beset automatically by calling LinearScale::SetAutoTicks() What you need to be aware of here is thatthis might slightly chance the min and max values you have specified. This is done so that the scalewill start and end on a major tick mark.

2.

The two images below illustrates this. They both have a manual scale, the left a manual ticks and the rightautomatic ticks.

Figure 1: Manual scale, manual ticks [src] Figure 2: Manual scale, automatic ticks using SetAutoTicks() [src]

6.8 Adjsuting the automatic tick marks

You can adjust the automtic tick marks by telling JpGraph how dense you want them to be. You use theGraph::SetTickDensity() method. You can set the density setting in four steps

TICKD_VERYSPARSE, Very few ticks• TICKD_SPARSE, Few ticks• TICKD_NORMAL, Standard number of ticks• TICKD_DENSE, Large number of ticks•

Taking the previous example with the manual scale but automatic ticks and using a denser ticks setting givesthe following result

10/07/2002 01:19:24 AM 64

Page 69: Jpgraph Manual

Figure 3: Manual scale with automatic ticks but with a denser tick settings. [src]

6.9 Adjusting labels on a text scale

In the following section we will work through an number of examples on how to manipulate labels on a textscale. Primarily we will investigate how to best handle the case where you have a large number of values.

As a remainder; Text scale is meant to be used on the X−axis when the X−axis doesn't have a numeric value,i.e you are only ineterested in linear ordering of the data. If you don't specify the labels manually they will beset automtically starting from 1 as the example below shows.

Figure 4: A simple bar plot using an automatic text scale [src]

To specify the labels on the X−axis as suitable text strings you call the method Axis::SetTickLabels() with anarray containing the text−labels. If there are more data points than labels the non−specified labels will begioven their ordinal number. If we augument the previous example with the name of the month we get thefollowing new example

10/07/2002 01:19:24 AM 65

Page 70: Jpgraph Manual

Figure 5: Manually specifying the text scale labels [src]

Tip: To get hold of localized version of the month names (or weekdays) you can use the DateLocal class available in the global variable $gDateLocale If nolocale has been specified the default locale for the installation will be used.

What happen now if we have a larger number of bars? Let's try with 25 bars and see what result we get.

Figure 6: A larger data set [src]

Not all to impressive. The labels are to close and they overlap. Hence it is not a good idea to sisplay everylabel. To adjust what labels are to be displayed you use the SetTextLabelInterval() method. The argument tothis method is the itervall between text labels. So to display only every 3 month you would add the line

Which would give the result shown below

10/07/2002 01:19:24 AM 66

Page 71: Jpgraph Manual

Figure 7: Displaying only every third label [src]

Much better, quite readable.

If we have an even larger data setit might not longer be meaningfull to display all the tick marks since theywould simple become to close. In JpGraph there is a possibility to specify that you only would like every n:thtick mark to be visible ( SetTextTickIntervall() ). For bar graphs using text scale however, that might not besuch a good idea since the tick marks are between the bars and the labels centered under the bars. If we onlywere to disply, say, every 3 tick mark it wouldn't look to good. Not that we can't do it, as the example belowshows, but it just doesn't look very good.

Figure 8: Displaying just every third tick mark. [src]

A better way to handle large data set is simply to hide the tick marks all together. Tick marks may be hiddenby calling the method Axis::HideTicks(); If we hide all the ticks on the X−axis we will get the result shownbelow

10/07/2002 01:19:24 AM 67

Page 72: Jpgraph Manual

Figure 9: Hiding all tick mark. [src]

More ... [ TBC ]

6.10 Adding arbitrary text strings to the graph

To add clarification or other information text strings to the graph you can add arbitrary lines of text anywhereyou like onto the graph. The text might have multiple lines and you can shoose the paragraph alignment.

To add text you have to create one or more instances of the Text() object and then add the text object to thegraph with the AddText() method.

The position of these text boxes are given as fraction of the width and height of the graph. When you arepositioning these text boxes you migt also choose what part of the text box should be considered the anchorpoint for the position you specify.

By default the anchor point is the upper left corner of the bounding box for the text.

To show some ways of positioning the text we use a very simple bar graph not to distact from the text. Wefirst just add a single text line with most of the settings their default value by adding the following lines to thegraph

$txt=new Text("This is a text");$txt−>Pos(0,0);$txt−>SetColor("red");$graph−>AddText($txt);

The result is shown below.

10/07/2002 01:19:24 AM 68

Page 73: Jpgraph Manual

Figure 1: Adding a single text string in the upper left corner [src]

Not too exiting. Let's make it more interesting by having a background color, using larger fonts and framingthe text box and adding a drop shadow to the text box by using the methods SetBox() and SetBox()

Figure 2: Making the text more interesting [src]

That's better. Now we get some attention. If you want to add a text with several lines you just need to separatethe lines with a newline ('\n' character). The default paragraph alignment is left edge but you can also use rightand center alignment.

As an illustration let's add a couple of more lines to the previous text, center the text box in the middle of thegraph and also use centered paragraph alignment for the text. To adjust the paragarph alignemtn of the textyou have to use the Text::ParagraphAlign()

10/07/2002 01:19:24 AM 69

Page 74: Jpgraph Manual

Figure 3: Text with multiple lines and centered paragraph alignment [src]

Of course there is no limit to the number of text string you can add to the graph.

6.11 Adding titles and footers to the Graph

Each graph can have up to three differenet titles accessed by the three properties

title1. subtitle2. subsubtitle3.

All of these three properties is a standard text object which means that you can have individual font, colors,margins and sizes of these tree titles.

The only thing you need to think of is that you probably want to add some extra margin to make room for thetitles (using Graph::SetMargin() )

The individual positioning of these titles are done automatically and will adjust to the font size beeing used.

If you for, aesthetic reasons, would like increase the distance from the top where the title is positioned (or theintra distance between title and sub title) you can use the Text::SetMargin() method. For example the line

$graph−>title−>SetMargin(20);

will set the distance between the top of the title string and the top of the graph to 20 pixels. If you instead callthe SetMargin() method for the subtitle it will adjust the distance between the top of the subtitle and thebottom of the title.

The titles will be positioned at the top and be centered in the graph. Each of these titles may have multiplelines each separated by a "\n" (newline) character. By default the paragraph alignment for each title iscentered but may of course be changed (using the ParagraphAlign()) method.

10/07/2002 01:19:24 AM 70

Page 75: Jpgraph Manual

Each graph can also have a footer. This footer is actually three footers. Left, center and right. The 'left' footeris aligned to the left, the 'center' at the bottom center and the right to the right.

Each of these three positions is a standard Text object which means you can change color, font and size as youplease individually on each of these footer positions.

You access the footer through the Graph::footer property as the following example shows

$graph−>footer−>left−>Set("(C) 2002 KXY");$graph−>footer−>center−>Set("CONFIDENTIAL");$graph−>footer−>center−>SetColor("red");$graph−>footer−>center−>SetFont(FF_FONT2,FS_BOLD);$graph−>footer−>right−>Set("19 Aug 2002");

Note: If you enable the brand timing argument you should leave the left footer empty.

6.12 Using background images

Insetad of having a single color background you can easily have an arbitrary image as the background. Theimage may be in either PNG, JPG or GIF format depending on what your installation supports.

A note on GD: If you are using GD 2.xx you must make sure that the define USE_TRUECOLOR is set to true. This is also the default. Failure to do so incombination with GD 2.xx will make the background image just look like a solid black square.

To use a specific image as the background you just have to use the method Graph::SetBackgroundImage()The arguments specify file−name, how the image should be positioned in the graph and finally the format ofthe image (if it is in JPG, PNG or GIF) format. If the format is specified as "auto" (the default) then theappropriate image format will be determined from the extension of the image file.

The file name is of course obvious but the second argument might not be. This arguments determine how theimage should be copied onto the graph image. You can specify three different variants here

BGIMG_ COPY This will just copy the image unchanged onto the graph from the top left corner.1. BGIMG_CENTER This will just copy the image unchanged onto the graph but it will center theimage in the graph.

2.

BGIMG_FILLFRAME This will scale the image to exactly fit the whole graph image.3. BGIMG_FILLPLOT This will scale the image to exactly fit just the plot area of the graph.4.

You might often find yourself wanting to use a background image as a "waterstamp". This usually meanstaking the original image, import it to some image editing program and then "bleeching" the color saturation,reducing the contrast and so on. Finally you save the modified image which you then use as a bacvkgroundimage.

This whole process can be automatically accomplished in JpGraph by using the method

10/07/2002 01:19:24 AM 71

Page 76: Jpgraph Manual

Graph::AdjBackgroundImage() which allow you to adjust color saturation, brightness and contrast of thebackground image.

For example, in the image below I have used the settings

$graph−>AdjBackgroundImage(...)

to achive the "watercolor" effect to avoid the image being too intrusive in the graph.

Figure 4: Example on using a watermark type background image [src]

Sidenote: The background image is my primary means of summer transportation. A 1998 Triumph Tiger. This bike is a nice 900cc quarter−of−a−metric−tonon/off−road bike. This is one of the few bikes I found which I can ride comfortable in despite me being 6' 4''.

Finally we like to mention that in the "/utils/misc/" directory you will find a small utility script called"mkgrad.php". Running this script presents you with a UI that makes it a breeze to create a gradient imagewhich then can be used as a background image (after you saved it of course).

The UI for the utility is so obvious that we won't discuss it further, we just show it below.

10/07/2002 01:19:24 AM 72

Page 77: Jpgraph Manual

The UI for the mkgrad.php utility

In the example below I have used this utility to get a more interesting plot area.

Figure 5: Example of the use of a gradient background [src]

6.13 Using callbacks for Plot marks

An interesting enhancement when using Plotmarks is the possibility to add a callback function to control thesize and color of the plotmarks.

This callback function will get called with the current Y−value (for the plotmark) as it's argument. As returnvalue the callback function must return an array containing three (possible null) values. The values returnedmust be

Plot mark Weight1.

10/07/2002 01:19:24 AM 73

Page 78: Jpgraph Manual

Plot mark Color2. Plot mark Fill color3.

The exact meaning of the parameters will of course depend on the type of plot marks being used.

The callback must be a global function and is installed with a call to PlotMark::SetCallback()

So for example to install a callback that changes the fill color for all marks with a (Y) value higher than 90you could add the lines

function MarkCallback($aVal) { if( $aVal > 90)

$fcolor="red"else

$fcolor=""; return array("","",$fcolor);}...$plot−>mark−>SetCallback("MarkCallback");...

As you can see in the above example we have left some of the return values blank. Doing this will just ignoreany change of these value and use the global settings for the plotmarks.

If you also let the (Y) value affect the size of the plot marks you can get what is sometimes known as a"balloon plot". The example below is basically a scatter plot that uses filled circles to mark the points. Aformat callback is then used to change the color and size depending on the Y−value for each plot.

10/07/2002 01:19:24 AM 74

Page 79: Jpgraph Manual

Figure 6: Creating a balloon plot by using plot mark callback function [src]

6.14 Formatting the axis

To get the exact type of axis you want in your graph there are a number of adjustments available for you. Youmay change, color, size, position and general apperance.

6.14.1 Standard two axis graphs

Assuming we start with the traditonal two axis graph, one X and one Y axis. You may then change theposition of each axis by calling Axis::SetPos($aPosition) You have to remember that you need to specify theposition on the other axis. SO you need to specify the world−coordinate for the position. By default the axisare each positoined at the 0−point on the other axis, i.e. the axis will cross at the 0,0 point in the graph.

In additio to the standard positioning you may also use the two special position markers "min" and "max".This will position the axis at the minimum (or maximum) position of the other axis.

For example, to make sure that the X−axis is always at the bottom of the graph (at lowest possible Y−value)you would have to add the line

$graph−>xaxis−>SetPos("min");

To change the color and width of the axis you have to make use of the Axis::SetColor() and Axis::SetWeight()methods.

Invisible axis Even though JpGraph (1.7) doesn't directly support "hidden" axis wher the labels are still drawn it is very easy to achive this effect by setting thecolors of the axis to be the same as the background. See the example barintex2.php in the Example directory. To completely hide an axis you can make use ofthe Hide()

10/07/2002 01:19:24 AM 75

Page 80: Jpgraph Manual

You might also want to add titles to the axis. This is done through the Axis::SetTitle() method. This is actuallyjust a shortcut for accessing the title proeprty direct. Axis::title::Set() which also allow you to set thealignment in one call.

By default the position of the title is to the far right for the X−axis and in the middle (and 90 degrees rotated)for the Y−axis.

You can adjust the position of the title with the help of the second argument to the Axis::SetTitle() method.

The possible positions are "high","middle" and "low" which refers to the scale values on the axis.

One common modification you might want to do to the title is to increase the margin between the axis and theactual title. This is often necessary to do for the Y−axis if the values displayed are large. You may adjust thedistance (in pixels) between the axis and the title by using the method Axis::SetTitleMargin()

So for example to increase the margin on the Y−axis you might add the line

$graph−>yaxis−>SetTitleMargin(40);

to your code.

Finally we mention something about the positioning of tick marks and labels on the axis. You have thepossibility to choose what side of the axis the tick marks and the labels should be at. For the X−axis this canbe specified as either on the the top (inside the plotarera) or at bottom (outside of the plotarea). In the sameway you can specify for the Y−axis if the labels ( or ticks) should be on the left or right side.

To adjust the label positioning you have to use the method Axis::SetTitleSide() and to adjust the position ofthe tick mark you have to use the method SetTickSide()

Note: There is also an alias for this method, SetTickDirection() which is deprecated from version 1.7 but kept for backwards compatibility.

Valid arguments for these methods are

SIDE_UP• SIDE_DOWN• SIDE_LEFT• SIDE_RIGHT•

For example, the following lines added to a script would change side of the labels and tickmarks for theX−axis.

10/07/2002 01:19:24 AM 76

Page 81: Jpgraph Manual

$graph−>xaxis−>SetLabelPos(SIDE_UP);$graph−>xaxis−>SetTickSide(SIDE_DOWN);

This technique is for example used if you position the X−axis at the top of the graph as the following exampleshows.

Figure 1: Example of both how to adjust the position of the X−axis as well as adjusting the side for the tick and axis title [src]

6.14.2 Scientific style axis

In scientific style plots it is often common to duplicate each axis so that all sides of the graph have a labeledaxis. This is of course also fully supported by JpGraph.

Before we continue we show a small example to illustrate this feature

Figure 2: Example of scientific axis [src]

10/07/2002 01:19:24 AM 77

Page 82: Jpgraph Manual

The example above shows the basic configuration. There are now several modifications you may do to theseaxis like

Choose if the labels should be inside ot outside the plotarea• Choose if the tickmarks should be inside or outside the plotarea•

The style of axis is determined by the method Graph::SetAxisStyle() The available type of axis are

AXSTYLE_SIMPLE, The standard two axis graph• AXSTYLE_BOXIN, Four axis scientific style with labels and tickmarks on the inside• AXSTYLE_BOXOUT, Four axis scientific style with labels and tickmarks on the outside•

6.14.3 Adjusting the position of the scale labels

How to adjust the actual labels are discussed elsewhere in this manual (see ???,???). Howver we like tomention here that you can adjust the label margin (distance betweeen the axis and the labels) with the methodAxis::SetLabelMargin()

to adjust the actual label format (like font, color, angle) you need to access the Axis::SetFont() and theAxis::SetColor() methods. If you investigate the Axis class you will discover more methods to adjust themany aspects of the axis layout.

As a final note we also mention the methods Axis::SetLabelAlign() and Axis::SetLabelAngle() This firstmethod is really only mentioned here for completenesss since it is mostly used for internal purposes. Howeveron som occasion you might want to adjust the alignment of the labels. By default they are centered in respectto the tickmark. By using the method you might override this positioning should you choose to do so.

The second of these methods adjusts the angle of the label in regards to the axis. This is very usefull forX−axis that have long labels.

6.14.4 Formatting the scale labels

[TODO] Graph::SetLabelFormatCallback(); Graph::SetLabelFormat();

6.14.5 Inverting the Y−axis

One good way of illutrsate the usefullness of label callbacks in a slightly different context is to show how wecan achieve the effect of an inverted Y−scale.

An inverted Y−scale has the lowest number at the top and the scale values increases downwards.

Even though JpGraph doesn't directly support this feature it is wuite easy to achieve with just a few extra linesof code in your image script.

Before we continue we give an example of what we are referring to.

10/07/2002 01:19:24 AM 78

Page 83: Jpgraph Manual

Figure 3: Inverted Y−axis [src]

Two achieve this effect there are two simple steps to take:

Negate all you Y−value in the data1. Create a callback that negates the scale labels so they appear to be positive.2.

And that's it! We refeer you to the code in the example above for the details.

6.15 Adjusting the autoscaling limits − grace value

By default the autoscaling algorithm tries to make best possible use of screen estate by making the scale aslarge as possible, i.e. the extreme values (min/max) will be on the top and bottom of the scale if they happento fall on a scale−tick. So for example doing a simple line plot could look like the plot shown in the below.

Figure 4: A typical graph with autoscaling and grace=0 [src]

However you might sometime want to add some extra to the minimum and maximum values so that there is

10/07/2002 01:19:24 AM 79

Page 84: Jpgraph Manual

some "air" in the graph between the end of the scale values and the extreme points in the graphs. This can bedone by adding a "grace" percentage to the scale. So for example adding 10% to the y−scale in the imageabove is done by calling the SetGrace() method on the yscale as in

$graph−>yaxis−>scale−>SetGrace(10,10);

These lines add a minimum of 10% to the top and bottom values of the scale. Note that we say "minimum"since depending on the specific tick values choose this might be a little bit more to make the end of the scalefall on an even tick mark.

Adding this line to the previous graph will result in the following example

Figure 5: Adding 10% grace value to top and bottom of the Y−scale [src]

Since we haven't adjusted the positoin of the X−axis it will remain at Y=0 which might not necessary be wahtwe would like so we therefor also add the line

$graph−>xaxis−>SetPos("min");

So that the X−axis always will remain at the lowest possible Y−value. Doing this will then result in theexample below

10/07/2002 01:19:24 AM 80

Page 85: Jpgraph Manual

Figure 6: Using grace but also adjusting the position of the X−axis [src]

6.16 Adding bands of pattern and color to graphs

As an additional way of emphasizing certain areas of the graph it is possible to add bands (either vertical orhorizontal) to any one of the standard X−Y coordinate system based graphs. A band is a rectangualr area thatstretches one entire axis. This means that if you define a band between X−coordinates 3 and 5 the band areawill occupy an area between the X−coordinates and the entiry Y−range.

At the time of this writing (current as of JpGraph 1.8) the table below illustrates the 8 basic types of patternsavailable. We will shortly show you how you can customize these patterns, To keep these examples clear wehave only used one pattern in each figure.

Figure 1: [src] Figure 2: [src]

Figure 3: [src] Figure 4: [src]

10/07/2002 01:19:24 AM 81

Page 86: Jpgraph Manual

Figure 5: [src] Figure 6: [src]

Figure 7: [src] Figure 8: [src]

To add a one of these patterns to your graph you need to call the method PlotBand::PlotBand() The argumentsis fairly easy to understand. The pattern you would like to use is specified by using the correct constant. Youcan see the name of the correct constants in the figures above. You also need to specify if the band shouldstretch along the vertical or horizontal axis as well as the min and max coordinates for the band. Ascoordinates you may also use the special values "min" and "max" which automtically sets the value to theminimum/maximum value of the scale. The specified numeric value will be automatically truncated to fitwithin the plot area.

We don't discuss the other arguments further here, instead we refer you to the class reference.

6.16.1 Customizing the patterns

All patterns can be customized by

... altering the colors of the band•

... altering the density of the patterns using the method PlotBand::SetDensity() The desnity isspecified as an integer in range 1 to 100 where a higher number means a higher density (smallerdistance between the lines). For example setting the density of the 3D plane above to 60 gives theresult

10/07/2002 01:19:24 AM 82

Page 87: Jpgraph Manual

Figure 9: Increasing the desnity in a pattern [src]

... enabling or disabling a frame around the pattern by using the method PlotBand::ShowFrame() Theband will ge given the same color as the band.

... finally you can change whether the band should be drawn on top of the plots or beneath, (by defaultthe bands are under the plots), using the PlotBand::SetOrder() as the following example show

Figure 10: Stroking the pattern on top of the plots [src]

Sidenote. 3D planes actually carry another possible modification. You can specify the vanish point to change the perspective used. You can't acces the

method to change the horizon directly but you can access it through

$band−>prect−>SetHorizon($aHorizon)

assuming that the band is a 3D plane.

To finish this section we give one final, more creative, example on how to use the bands.

10/07/2002 01:19:24 AM 83

Page 88: Jpgraph Manual

Figure 11: Combining 3D plane, solid band and a sttaic line [src]

6.17 Adding static lines to the plot

In addition to the bands you can also add static lines to the graph. An example of that is actually shown infigure 11 above. You create a line as an instance of class PlotLine . So for example the lines

$sline = new PlotLine(HORIZONTAL,0,"black",2);$graph−>Add($sline);

will add a 2−pixel wide horizontal static line at Y−position zero.

10/07/2002 01:19:24 AM 84

Page 89: Jpgraph Manual

7 Working with non X,Y−plotsNon X,Y plots includes

Pie plots (2D and 3D)• Radar plots• Gantt charts•

The fundamental difference is that these classes that each one makes use of an extended version of the basicGraph class.

To create 2d or 3d pie plots you must use the PieGraph class• To create radar plots you must use the RadarGraph() class• To create gantt plots you must use the GanttGraph() class•

7.1 Radar plots

Spider plots are most often used to display how a number of results compare to some set targets. They makegood use of the human ability to spot symmetry (or rather un−symmetry) . the figure below show an exampleof a spider (sometimes called a web−plot). Spiderplots are not suitable if you want very accurate readingsfrom the graph since, by it's nature, it can be difficult to read out very detailed values.

Figure 1: A typical radar graph with two plots [src]

There is one axis for each data point• Each axis may have an arbitrary title which is automatically positioned• A spider plot may be filled or open• You can control color, weight of lines as you are already used to• A spider plot can, as usual, have a title and a legend• The first axis is always oriented vertical and is the only axis with labels• Grids may be used (dashed in the figure above)• You may have ticks (although suppressed in the figure above• You can control the size and position within the frame of the graph• You may have several plots within the same graph•

10/07/2002 01:19:24 AM 85

Page 90: Jpgraph Manual

In the following section we show how to draw both simple and complex radar graph. As we will show all thesettings will follow the same pattern as for the more standard linear graphs.

7.1.1 Simple radar plots

Let's start by creating a very simple radar plot based on 5 data points using mostly default values.

As the first thing you must remember to include the extension module that contains the radar plot."jpgraph_radar.php".

A very simple radar plot is created by the code

(File: radarex1.php)<?phpinclude ("../jpgraph.php");include ("../jpgraph_radar.php");

// Some data to plot$data = array(55,80,46,71,95);

// Create the graph and the plot$graph = new RadarGraph(250,200,"auto");$plot = new RadarPlot($data);

// Add the plot and display the graph$graph−>Add($plot);$graph−>Stroke();?>

and would give the result

Figure 2: A first very simple radar plot using default settings [src]

To change the size and position of the radar graph is similair to the pie plot and you do it by using themethods SetSize() and SetCenter()

10/07/2002 01:19:24 AM 86

Page 91: Jpgraph Manual

If you want a filled radar plot you need to specify the fill color with the method SetFillColor() The followingexample shows these methods in action

Figure 3: Changing size, position and adding fill color to the radar plot. [src]

7.1.2 Specifying titles for the axis and legends for the plots

We normally would like something more meaningful as description of each axis than it's number. Specifyingthe titles are accomplished through the use of the method SetTitles() of the graph. Let's say that each axiscorresponds to a month. We could then use the code

$titles = $gDateLocale−>GetShortMonth();$graph−>SetTitles($titles);

As you can see the way radar plot is constructed will assign the titles (and plot points) in a counter−clockwisedirection. If you want them in clock−wise order you will have to inverse your input data array as well as thetitle array.

To specify a legend you (as with the other plot) make use of the SetLegend(); method on each radar plot.

7.1.3 Adding gridline to the radar plot

Each major ticvk mark can also be connected togehter to create a grid. The grid is accessed through the 'grid'property of the graph. To enable the grid and set the line style to "dotted" you would have to add the lines

$graph−>grid−>Show();$graph−>grid−>SetLineStyle("dotted");

and would result in the followin graph

10/07/2002 01:19:24 AM 87

Page 92: Jpgraph Manual

Figure 4: Adding dotted gridlines to the graph [src]

By design the plot is above the gridline but beneath the axis in image depth, hence some part of the gridlinesare hidden.

To have the gridlines more "visible" just change their color, say to, dark red by invoking the SetColor()method on the gridlines which would give the following result

Another simple change we could do would be to just change the background color of the radargraph. This is(not surprisingly) done by a call to the method SetColor() invoked on the graph object.

Figure 5: Changing the background color [src]

7.1.4 Adding several plots to the same radar graph

You can easily create several radar plot which are added to the same radar graph. The thing to remember isthat if you use filled radar plots and they overlap each other that the order which they are added will be theorder they are drawn.

A simple example of this is shown below

10/07/2002 01:19:24 AM 88

Page 93: Jpgraph Manual

Figure 6: Several radar plots in one radar graph [src]

7.2 Pie plots

So fvar we have just show plots based on an X−Y coordinate system. This is not the only types of graphs youcan create with JpGraph. Another common type is Pie plots. JpGraph supports both 2D and 3D pie plots. For2D pie plots there are also 2 versions, but more on that later.

The main difference as compared to the X−Y plots is that to all pie plots are added to the PieGraph() insteadof the Graph() object we used for the X−Y graphs we have drawn so far. For this you must first include the"jpgraph_pie.php" in your script (or "jpgraph_pie3d.php" if you want to use 3−dimensional pies).

Below you cane see the code needed to create the simplest possible pie graph just using the default settings.

include ("../jpgraph.php");include ("../jpgraph_pie.php");

$data = array(40,60,21,33);

$graph = new PieGraph(300,200);$graph−>SetShadow();

$graph−>title−>Set("A simple Pie plot");

$p1 = new PiePlot($data);$graph−>Add($p1);$graph−>Stroke();

The above code would give the following pie graph

10/07/2002 01:19:24 AM 89

Page 94: Jpgraph Manual

Figure 1: The simplest possible pie graph [src]

There is a few things worth noting here

By default all pie slices have the percentage shown just outside the slice.• The colors are automatically assigned to the slices.• The pie have the edges marked by default• The fisr slice start at 0 degrees (3 a'clock)•

You can change allmost all aspects of apperance of the pie graphs. For example you could change :

Change the angle for the first slice, (PiePlot::SetStartAngle())• Remove the border lines around the pie (PiePlot::ShowBorder())• Change the color of the border (PiePlot::SetColor(),• Change the colors of the slices (PiePlot::SetSliceCOlors())• Change the size and position of the pie (PiePlot::SetSize(), PiePlot::SetCenter())• Adjust the labels for the slice (color, font, format, position ) by accessing the value property of pieplots, for example (PiePlot::value::SetFont(), You can read more about label formatting and how tochange what is displayed as a value further down in this chapter.

The next simplest addition we can do is to add a legend to the pie graph. We do this by using theSetLegends(); method. By adding the legends to the previous example we get the following image

Figure 2: Adding a legend to the pie graph [src]

10/07/2002 01:19:24 AM 90

Page 95: Jpgraph Manual

(In the figure above we also moved the center of the pie slightly to the left to make more room for the legendbox.)

The text for the legends can also contain printf() style format strings to format a number. This number passedon into this string is either the absolute value of the slice or the percentage value. How to switch between theis describe further down in this chapter.

The next change you might want to change is the size and position of the Pie plot. You can change the sizewith a call to SetSize(); and the position of the center of the pie plot with a call to SetCenter(); The size can bespecified as either an absolute size in pixels or as a fraction of width/height (whatever is the smallest). Theposition of the pie plot is specified as a fraction of the width and height.

To put the size and positioning API to use we will show how to put several pie plots on the same pie graph. Inthe following example we have also adjusted the legends of the slice values to use a smaller font.

What we do in this example is quite simple, create 4 pie plots, make them smaller and put them in the fourcorner of the graph. This will give the result as shown in the following example.

Figure 3: Multiple pie plots in the same pie graph [src]

7.2.1 Creating 3D pie plots

So far we have only made use of 2D pie plots, creating 3D pie plots is no more difficult. Instead of creatingthe plots with a call to PiePlot() you create the plots with a call to PiePlot3D() If we just take the first simplepie plot and replace the call to PiePlot() with a call to PiePlot3D() we get the following result.

10/07/2002 01:19:24 AM 91

Page 96: Jpgraph Manual

Figure 4: A first example of a 3D pie plot [src]

3D Pie plots have the same possibilities as the normal pie plots with the added twist of a 3:rd dimension. Youcan adjust the perspective angle with the method SetAngle() So for example to make the pie more "flat" youjust set it to a smaller angle. Setting the perspective angle to 20 degrees in the previous example will give thefollowing result.

Figure 5: Adjusting the perspective angle [src]

7.2.2 Exploding pie slices

One way to attract attention to some specific piece of information in a pie chart is to "explode" one or moreslices. Both 2D and 3D pies support exploding one or several slices.

Explding slices is accomplished by the methods Explode() and ExplodeSlice() The first method is used if youwant to explode more than one slices and the second is a shorthand to make it easy to just explode one slice.

For example to explode one slice the default "explode" radius you would just have to say

$pieplot−>ExplodeSlice(1)

The above line would explode the second slice (slices are numbered from 0 and upwards) the default amount.Doing this to the two previous example would result in

10/07/2002 01:19:24 AM 92

Page 97: Jpgraph Manual

Figure 6: Exploding one slice [src] Figure 7: Exploding one 3D slice [src]

To explode all slices at once you can use the PiePlot::ExplodeAll() method. If you want to explode severalslices you can use the PiePlot::Explode() method and supply a suitable array argument.

7.2.3 Specifying and adjusting labels on pie plots

By default the values shown just outside the pie for each slice are the percentage value for each slice. If youinstead wanted the absolute value you would just have to use the SetLabelType() method. So to use theabsolute value you would call

$pieplot−>SetLabelType("PIE_VALUE_ABS");

Furthermore you could enhance the formatting of the value by either using a printf() style format string (usingSetFormat() ) or by providing a formatting function callback (using SetFormatCallback() ) for doing moreadvanced formatting.

You can also adjust the position of the labels by means of the PiePlot::SetLabelPos() method. The argumentto this method is either the fraction of the radius or the string 'auto'. In the latter case JpGraph automaticallydetermines the best position and the the first case The following example illustrates this

Figure 8: Example of adjusting the position of the labels for the slices [src]

10/07/2002 01:19:24 AM 93

Page 98: Jpgraph Manual

If this formatting is not enough you can also "manually" specify the labels for each slice individually. You dothis by using the PiePLot::SetLabels() method. This will let you specify individual text strings for each label.In each specification you can also add a printf() formatting specification for a number. The number passed onwill be either the absolute value for the slice or the percentage value depending on what was specified in thecall to SetLabelType()

The SetLabels() method can also take a second parameter, the label position parameter. This is just a shortcutto the SetLabelPos() as described above. By default the position will be sert to 'auto' if not explicetelyspecified.

Note: The alignment of the labels will be different depending on wheter they are inside or outside the pie. When inside the center of the strings will be alignedwith the center of the slice at the specified fraction of the radius. When positioned outside the alignment will depend on the angle to avoid that the labelsinadvertedly writes over the pie.

7.2.4 Specifying slice colors and using themes

Another typical change would be to change the colors of the slices. There are two fundamental ways of doingthis. You either manually specify the colors for the slices as an array using the method SetSliceColors() If youspecify fewer colors than the number of slices they will just wrap around.

Another way is to use one of the pre−defined color "themes". This is just a predefined set of colors that will beused for the slices. You choose what "theme" you like to use with the method ( SetTheme() ) At the time ofthis writing the available themes are

"earth"• "pastel"• "sand"• "water"•

The following example shows the same pie using the different "themes" in order.

Figure 9: [src] Figure 10: [src] Figure 11: [src] Figure 12: [src]

A complete color chart of all available colors in the different themese can be found here

Another simple change is to remove the border ( or change it's colors ) that separates each slice. This can bedone by a call to ShowBorder()

10/07/2002 01:19:24 AM 94

Page 99: Jpgraph Manual

7.2.5 Adding drop shadows to the slices

An additional visual enhancements can be made by adding a drop shadow to the individual slices. This isaccomplished by means of the PiePlot::SetShadow() method. Adding a drop shadow is often more affective ifthe pie has one or more slices exploded as the following example shows

Figure 13: Adding a drop hadow to the slices [src]

7.2.6 Another variant of 2D Pie plots

As mentioned in the beginning there are two versions of the 2D pie plots. The normal pie plot created as aninstance of class PiePlot and a variant created as an instance of class PiePlotC

This variant is an extension of the standard PiePlot in the sense that it also have a filled circle in the center.The following example illustrates this

Figure 14: Example of the variant of pie plot with a filled center circle [src]

10/07/2002 01:19:24 AM 95

Page 100: Jpgraph Manual

Since the PiePlotC is an extension to the basic pie plot all the normal formatting you can do for pie plots youcan also do for the PiePlotC .

The additional formatting only concerns the filled middle circle. You have the option of adjusting size, fillcolor and all font properties. You perform these operations with the methods

PiePlotC::SetMidColor() Set fill color of mid circle

PiePlotC::SetMidSize() Set size (fraction of radius)

PiePlotC::SetMidTitle() Set title string (may be multi−lined)

PiePlotC::SetMid() Set all parameters in a single method callIn addition to the normal CSIM for PiePlot:s the center area is also a CSIM hotspot. You specify the targetCSIM with a call to PiePlotC::SetMidCSIM()

The next example shows an example with some more innovative formatting. In this example we have :

hidden the frame around the pie graph• exploded all the slices• added drop shadow to the individual slices (and the center filled circle)• specified individual multi line labels.• changed the font for the title to a TTF font.•

Figure 15: PiePlotC with some more innovative formatting to make it more interesting. [src]

10/07/2002 01:19:24 AM 96

Page 101: Jpgraph Manual

8 Using image maps with JpGraphImage maps, or client side image which are used in JpGraph, gives you the opportunity to create hot−spots inthe graphs which allows you to build a set of "drill−down" graphs.

In the following I will make the assumption that the reader is familiar with the basic concepts of client sideimage map in HTML. If you are not familiar you can a) read some book that explains this or b) pay me lots ofmoney to explain it to you :−)

8.1 The basic structure of an image map script

The standard structure for a HTML page using client side image maps would be something along the lines of

// Image map specification with name "mapname"<MAP NAME=...>... specification ...</MAP>

// Image tag<img src="..." ISMAP USEMAP="mapname">

This poses some interesting questions.

Since we normally call the graphing script directly in the <img> tag how do we get hold of the image map(which is available only in the image script> in this "wrapper" script?

In JpGraph there is actually two ways of solving this.

Use the preferred "builtin" way using the modified Stroke() method Graph::StrokeCSIM() instead ofthe standard Graph::Stroke() method.

1.

Directly use the Graph::GetHTMLImageMap() which gives you fine control at the expense of morecomplex coding.

2.

The first (and preferred) way modifies the stroke method so that instead of returning an image (like thestandard Stroke() method) StrokeCSIM() actuallty returns a HTML page containing both the image mapspecifiaction and the correct <IMG> tag.

This of course means that you have to treat an image map returning image script diffrently from a non−CSIMimage script, for example you can't use it directly as the target for the "src" attribute of the <IMG> tag.

8.2 Specifying targets for image map plots

To turn a standard image script into a CSIM script the first thing you need to do is to supply the appropriateURL targets for the hotspots in the image.

What the hotspots represent depends on the type of plot you are doing. The following plot types supportimage maps.

10/07/2002 01:19:24 AM 97

Page 102: Jpgraph Manual

Line plots. Markers are hotspots.• Scatter plot. Markers are hotspots.• Pie Plots and 3D Pie plots. Each slice is a hotspot• All types of Bar graphs. Each bar is a hotspot•

To specify a link for each hotspot you have to use the SetCSIMTargets() method for each plot in the graphyou want to have hotspots.

The two arguments to this method are

$aTargets, an array of valid URL targts. One URL per hotspot, for example if you have a 10 valuesbar plot you need 10 URLs

$aAlts, an array of valid alt−texts. Usually showed by most browsers if you hold you pointer over ahotspot.

8.3 Using StrokeCSIM()

The simplest way of creating a creating a CSIM image is with the StrokeCSIM() method. As mentionedbefore this method actually returns a (small) HTML page containing both the image−tag as well as the imagemap specification. Hence you can't use the script directly in an image−tags src−property.

You can create an CSIM in two ways

Use the CSIM image script as the target in a standard anchor reference, for example 1.

<a href="mycsimscript.html">

This has the drawback that your image page will only contain the image and nothing else.The other way let's you include the image in an arbitrary HTML page by just including the imagescript at the wanted place in your HTML page using a standard "include" php statement. For example

2.

<h2> This is an CSIM image </h2>

<?phpinclude "mycsimscript.php"?>

Note: If you have several CSIM images on the same page you must use 'include_once' in the scripts when you include "jpgraph.php" and the other jpgraphlibrary files since you will otherwise in effect try to include these libraries multiple times on the same page and get a "Already defined error"

The process to replace Stroke() with StrokeCSIM() is simple. You just need to make the replacement andsupply some arguments to StrokeCSIM(). The only required argument is the first which must be the name ofthe actual image script file including the extension. So for example if your image script is called"mycsimscript.php" you must make the call

$graph−>StrokeCSIM('mycsimscript.php')

10/07/2002 01:19:24 AM 98

Page 103: Jpgraph Manual

Sidebar: Why do I need to supply the image script name? The reason is that in the creation of the HTML page which is sent back we need to refer to the scriptin the image tag. So why not use the PHP_SELF reference? The problem with PHP_SELF is that in the case where we include the image−script in an HTMLpage and use the PHP_SELF we will get the name of the HTML page and not the actual script in which the PHP_SELF is used.

The other arguments to StrokeCSIM() are optional. Please note that if you are using several CSIM images inthe same HTML page you also need to specify the image map name as the second parameter since all imagemaps must be unique since they are used to bind one image to one image map. Please see the class referenceStrokeCSIM() for details.

8.4 Examples of Image maps

The examples below shows how different plot types uses image maps. Please note that none of the URLs inthe image points to any valid page. SO you will get an "404 Page not found" if you click on the images. Anice feature in most browsers is that if you hold the pointer on a CSIM point in the image you will see thealt−tag as a small popup. In these examples that popup is used to display the value for the particular part ofthe graph.

8.4.1 Client maps with Bar graphs

8.4.2 Client maps with Pie graphs

10/07/2002 01:19:24 AM 99

Page 104: Jpgraph Manual

8.4.3 Client maps with Scatter graphs

8.5 How does StrokeCSIM() work?

Knowledge of the exact technical details of the way StrokeCSIM() works is probably not needed by manypeople but for completeness we outline those details in this short section.

The fundamental issue we have to solve is that we must be able to call the image script in two modes. Whenthe user includes the image script the StrokeCSIM() method should return the HTML page but when theimage script is later called directly in the image tag it must not return an HTML page but rather the actualimage.

The way this is solved is by using one HTTP argument which is passed on automatically when we use theimage script name in the image−tag.

If you look at the generated HTML you will see that the argument to the src−property of the image tag is notsimply the script name but the script name with a additional argument.

In the JpGraph internal code this pre−defined argument is checked for and if it exists the image is send backand not the HTML page.

The name of this argument is defined by a DEFINE() statement in JpGraph. The define is _CSIM_DISPLAY.

10/07/2002 01:19:24 AM 100

Page 105: Jpgraph Manual

8.6 Getting hold of the image map

In the case where you want to store the image on disk and later use it in an img−tag you need to get hold ofthe image map. For this you will have to use the function Graph::GetHTMLImageMap()

An example of the use of this is shown below. With these lines the image will be written to a file. The scriptthen returns a HTML page which contains the Client side image map and an img−tag which will retrieve thepreviously stored file.

$graph−>Stroke("/usr/local/httpd/htdocs/img/image001.png");echo $graph−>GetHTMLImageMap("myimagemap001");echo "<img src=\"img/image001.png\" ISMAP USEMAP=\"#myimagemap001\"border=0>";

8.7 Image maps and the cache system

Unfortunately you can't use the automatic Jpgraph cache system together with client side image maps. Thereason for this is that the cache system would have to be extended to also cache the actual HTML maps.Without doing this we could not make use of the cached image.

However, as was shown in the previous example you can still manually store the image in a file and get holdof the HTML image map manually. Using this method you could yourself store away the HTML pagecontaining the img−tag together with the map so you don't have to re−generate the image each time. Thiscould come in handy if you work a lot with 3D pie graphs since they are computational expensive.

10/07/2002 01:19:24 AM 101

Page 106: Jpgraph Manual

9 Gantt charts

9.1 Purpose of this tutorial

This tutorial aims to introduce how to use the Gantt chart module of JpGraph. The only assumptions made isthat you have a working knowledge of PHP and have a basic understanding of JpGraph, most likely youshould have read the JpGraph documentation.

This tutorial specifically will not teach you how to install PHP, Apache, TTF fonts, the GD library or anyother infrastructure that you need to make JpGraph work.

You should have obtained a copy of JpGraph together with its associated documentation and have access to aWEB server on which you have tried (and succeeded!) to run a few of the example graphs supplied. If youhave successfully completed that you are all set to start reading this tutorial.

This tutorial will therefore only focus on and go to some great length to introduce you to all features of theJpGraph Gantt module. Enjoy!

9.2 Some notes on format and files used in this tutorial

All source code displayed in the tutorial are separate files which are included in the same directory as thistutorial. It is always the exact code that generated the image that is shown and not a hand made copy. ThePHP source is syntax highlighted to make it easier to follow. The actual file name appears for the code canalways be found in the first line of the displayed source.

Sometimes (to save space) I don't include the full source if the example is just a very minor modification to aprevious example. In that case I just show the difference. For all images in this tutorial the full source canalways be seen by clicking on the "[src]" tag at the end of the caption for that image.

My hope is that these convention will make it easier to follow the tutorial and will give a balanced mix of fullsource versus space and ease of reading.

9.3 Why use Gantt charts?

The cynical view: To explain why your project is over−due and over−budget.

The pragmatic view: To keep management of our back and know what we have forgotten

The common view: As a tool to help identify project issues and highlight problem areas.

Basically, Gantt charts are used to show the state of a number of activites (possible grouped) against time.

10/07/2002 01:19:24 AM 102

Page 107: Jpgraph Manual

9.4 Capabilities in JpGraph Gantt module

Automatic and manual scaling of date• Gant charts can be automatically sized according to the number of bars and scale used. This meansyou don't have to supply a specific size when creating a graph.

Unlimited number of activities• Supports platform independent Week number calculation according to ISO:8601• Rich possibility to display a variety of scales or combination of scales supports both day, week,month, year. Each scale header is totally configurable in terms of font, size, color, background etc

User configurable date format in the scale headlines• Scales have "intelligent" grids• Supports title and subtitle with user specifed font, size and color• Activity bars can have multiple patterns and colors• Activity bar may have shadows• Activity bars can have internal progress bars displayed to show how much of a given task has beenaccomplished

Activity titles can have individual fonts, colors and backgrounds• Activity bars can have captions• Activity bars can have specified left− and right end markers• Bar heights can be specified in absolute pixels or in percent of the activity line width• Supports milestones with many different marks• Supports vertical marker lines with text• Can easiliy be localized• Fully OO API which makes the API consistent and easy to learn• ... and more•

9.5 A simple Gantt chart

Time to show you an example of a Gantt chart and how easy it is to make one. Lets make it the simplestpossible gantt chart. One activity, named "Project", which lasts from "2001−11−01" to "2002−02−20".

All it takes to do this (using default values for everything) is the following code.

(File: ganttex00.php)<?phpinclude ("../jpgraph.php");include ("../jpgraph_gantt.php");

// A new graph with automatic size$graph = new GanttGraph(0,0,"auto");

// A new activity on row '0'$activity = new GanttBar(0,"Project","2001−12−21","2002−02−20");$graph−>Add($activity);

// Display the Gantt chart$graph−>Stroke();

10/07/2002 01:19:24 AM 103

Page 108: Jpgraph Manual

?>

The resulting image is shown in Figure 1 below.

Figure 1: Your first simple Gantt chart. [src]

Let's note a few things with the above image and code:

You always need to include both jpgraph.php and jpgraph_gantt.php• A bar is specified a minimum of four parameters, vertical position (more about that in a second), atitle, start and end date.

If you don't specify a size for the image it will be automtically decided based on the min and maxdates for the bars rounded to a full week.

By default the week and day scale are displayed.• Weekend background are displayed default in a slightly gray color• Sundays are written in red.• Weeks are numbered according to ISO 8601• Activity bars are rendered as blue stripes on a white background by default.•

So, lets start making this graph a little bit more interesting. First we are going to add a title, then we will add amonth scale and finally we will change the color of the bar.

All that is taken care of in the code below.

(File: ganttex01.php)<?phpinclude ("../jpgraph.php");include ("../jpgraph_gantt.php");

$graph = new GanttGraph(0,0,"auto");$graph−>SetShadow();

// Add title and subtitle$graph−>title−>Set("A nice main title");$graph−>title−>SetFont(FF_ARIAL,FS_BOLD,12);$graph−>subtitle−>Set("(Draft version)");

// Show day, week and month scale$graph−>ShowHeaders(GANTT_HDAY | GANTT_HWEEK | GANTT_HMONTH);

10/07/2002 01:19:24 AM 104

Page 109: Jpgraph Manual

// Instead of week number show the date for the first day in the week// on the week scale$graph−>scale−>week−>SetStyle(WEEKSTYLE_FIRSTDAY);

// Make the week scale font smaller than the default$graph−>scale−>week−>SetFont(FF_FONT0);

// Use the short name of the month together with a 2 digit year// on the month scale$graph−>scale−>month−>SetStyle(MONTHSTYLE_SHORTNAMEYEAR2);

// Format the bar for the first activity// ($row,$title,$startdate,$enddate)$activity = new GanttBar(0,"Project","2001−12−21","2002−02−20");

// Yellow diagonal line pattern on a red background$activity−>SetPattern(BAND_RDIAG,"yellow");$activity−>SetFillColor("red");

// Finally add the bar to the graph$graph−>Add($activity);

// ... and display it$graph−>Stroke();?>

The resulting image is shown in Figure 2 below.

Figure 2: Making the Gantt chart a little bit more interesting with title and more colors. [src]

From the above example you might note a few things

The margins adjust automtically to the added title and subtitle• The height of the scale headers adjust automatically when you change the font.• You have great flexibility in choosing what format the scale labels will have. If you for examplewanted the full 4 digit year in the month header all you have to change is use the constantMONTHSTYLE_SHORTNAMEYEAR2 in the code above to

10/07/2002 01:19:24 AM 105

Page 110: Jpgraph Manual

MONTHSTYLE_SHORTNAMEYEAR4You have full freedom of manipulating headers in terms of font, color, background and size.•

To show that this is really simple let's show the full year in the month, and set the header style to be white texton a dark blue background by adding the lines

// Use the short name of the month together with a 4 digit year// on the month scale$graph−>scale−>month−>SetStyle(MONTHSTYLE_SHORTNAMEYEAR4);$graph−>scale−>month−>SetTextColor("white");$graph−>scale−>month−>SetBackgroundColor("blue");

to the code above. The resulting image is shown in Figure 3

Figure 3: Enhancing the scale headers. [src]

9.6 The structure of a Gantt chart

A Gantt chart is made up of four distinct areas.

On the left side there is the activity title column.1. On the top there is the scale headers (up to four headers may be displayed)2. The actual plot area where all the Gantt bars and markers go3. The margin area, where for example the titles are shown4.

Since a Gantt chart inherits all the usual properties of a JpGraph Graph() you have the access to the samemethod to formatting the image as before. For example to have a shadow around the image you callGraph::SetShadow() and to set the margin color you can use Graph::SetMarginColor(). Please refer to thereference documentation for a full list of supported features.

To create a Gantt chart you add objects to it. As of this writing you may add the following object by the use ofthe GanttChart::Add() method

Gantt bars (indicates the length of an activity)• Milestones, a single mark at a specific date• Vertical line, might be use to mark phases in projects•

10/07/2002 01:19:24 AM 106

Page 111: Jpgraph Manual

All these objects may be extensivly modified in terms of formatting. You can specify color (both fill− andframe color), size, titles, style and patterns and so on. All these objects comes with (in my mind) sensibledefault so you don't have to specify a lot of parameters. But if you need a fine grain control or if you disagreewith my taste you can.

9.7 Creating a GanttChart

You create a new Gantt Chart with a call to GanttChart(). The signature for GanttGraph is the same as forordinary JpGraph graphs, i.e

function GanttGraph($aWidth,$aHeight,$aCachedName,$aTimeOut,$aInline)

The only real difference is that for GanttCharts you can specify one or both of the dimension parameters(width and height) as −1 in which case that dimension will be automatically sized determined by scale andfonts choosen. The following examples shows some possible ways of creating a new graph

$graph=new GanttGraph()The size of the graph will be determined automtically, no caching will be used and the graph will begenerated inline.

$graph=new GanttGraph(−1,−1,"auto")The size of the graph will be determined automtically, caching will be used (the name will be basedon the script name), no timeout will be used and the graph will be generated inline

$graph=new GanttGraph(450,−1,"auto",5)Same as the previous entry but the width is fixed to 450 points and the cached image will have atimeout of 5 min.

$graph=new GanttGraph(−1,−1,"auto",5,false)The image will not be generated inline, only the cache will be updated if it has timed out, otherwisenothing will happen.

Since GanttGraph() inherits all the methods (that make sense for GanttGraph) from Graph you can specifyshadow, color etc of the general frame.

9.8 Positioning objects in the Gantt plot

Bars and Milestones need both a vertical position and a horizontal position. The horizontal start position isspecified as a date, e.g. "2001−06−23", and the vertical positions are specified as a number [0,1,2,3,...]. Thisvertical number indicates the position from the top where the object should be placed. To understand this youmight imagine a number of "invisible" horizontal bands with a certain height. If you specify 0 as the verticalposition the bar will be placed in the first band, specify 3 and the bar will be placed in the fourth band and soon.

It is perfectly legal, and perhaps even desirable to leave "gaps" when laying out bands to group relatedactiviies. So, for example you could have three activities/bars at positions 1,2,3 and then another 2 bars atposition 6,7 leaving band 0,4,5 empty.

10/07/2002 01:19:24 AM 107

Page 112: Jpgraph Manual

All these "invisible bands" have the same height (equspaced). The height of each band is automaticallydetermined and depends on both the method of layout ( as specified by (GanttChart::SetLayout()) and theindividual heights of the individual bars and titles. The rules are quite simple:

If you use layout=GANTT_FROMTOP (the default and most common) the height will equal theheight (+ a margin) of the highest gantt bar. The height calculation of each bar takes into accout boththe actual bar, the title, and any left− right−marks (more about that later) that may be present. Thename "fromtop" refers to that when you have explicetly specified a height the bars will usually beadded from band 0 and onwards and hence beeing added from the top. (This might leave empty spaceat the bottom of the plot area in the graph if the height of the graph has been explicetly specified).

If you use layout=GANTT_EVEN the bars are evenly (hence the name) spread out over the availableheight in the gantt chart and no consideration is taken of the individual bars heights. Note that if youuse automtic sizing you cant use even layout. It just doesn't make sence. Even layout is for those caseswhen you deliberately specify a very large image and whant the bars evenly distributed using the fullheight.

9.9 Gantt bars

The most common of all object in a Gantt chart is of course the activity bar (GanttBar()). In terms offormatting this object has a very large flexibility. The full signature for the GanttBar constructor is

function GanttBar($aVPos,$aTitle,$aStart,$aEnd,$aCaption,$aHeight)

$aVPos The vertical position for the bar, [0..n]

$aTitle Title for the activity

$aStart Start date for the activity given as string, e.g "2001−09−22"

$aEnd End date for activity given as either a date (a string) or as the duration (in days) of theactivity, e.g both "2001−10−15" and 20.5 are valid inputs

$aCaption Text string (caption) to appear at the end (right side) of the bar

$aHeight Height of bar given as either a value in range [0,1] in which case this is interpretated aswhat fraction of the vertical position should the bar occupy. The height can also be given inabsolute pixels [1..200]

9.9.1 Specifying vertical position

As described above vertical positions are specified as a numeric value [0..n] where 'n' is an arbitrary constant.(For practical purposes n is most likely < 100)

Using our previous example we will illustrate this parametger by changing the position of our 'Project' activityto position 7. Therefor we change the call to GanttBar() to

$activity = new GanttBar(7,"Project","2001−12−21","2002−02−20");

and we then get the chart as shown below in Figure 4.

10/07/2002 01:19:24 AM 108

Page 113: Jpgraph Manual

Figure 4: Changing the vertical position to 7 [src]

Note that the height of each position (vertical position) will depend on the actual height of the bar.

9.9.2 Specifying start and end position for a bar

Start of bars are given as a date string. The formar depends on the current locale. Examples of valid datestrings are

"2001−10−22"• "22 October 2001"• "22 Oct 2001"•

Even if several format are supported it is recommended to use all numeric dates, i.e in the form"2001−10−22".

Specifying the end position may be done in two different ways, either by the end date in the same way as forthe start date. The other way is to specify the length of the activity in number of days (and fractions thereof).Examples of valid end dates are:

"2001−11−15"• "15 Nov 2001"• 22, (specifies duration of 22 days)• 22.7, (specifies duration of 22.7 days)•

Note: Duration is specified as numerical values and not strings.

10/07/2002 01:19:24 AM 109

Page 114: Jpgraph Manual

9.9.3 Milestones

Milestones are similair to bars but have no end date since milestones just apply to one single date. Milestonesare created much the same way as activities but using method MileStone() instead.

The full signature for milestones are

function MileStone($aVPos,$aTitle,$aDate,$aCaption)

$aVPos The vertical position for the bar, [0..n]

$aTitle Title for the activity

$aDate Date for the milestone

$aCaption Text to the right of the milestoneValid milestones are for example

$milestone = new MileStone(3,"Code complete","2001−12−01");

$milestone = new MileStone(3,"Codecomplete","2001−12−01","(2001−12−01)");

By default milestones are rendered as a filled "Diamond" shape. This may be optionally modified. The actualshape is specified by the 'mark' property of milestone which is an instance of the PlotMark() class (same classresponsible for the marks in line graphs).

To change the shape of a milestone to, say a triangle, you use the SetType() method as in

$milestone−>mark−>SetType(MARK_DTRIANGLE)

Let's put this into practice and add a milestone to our previous example by adding the followinf two lines ofcode which result in Figure 5 shown below.

10/07/2002 01:19:24 AM 110

Page 115: Jpgraph Manual

Figure 5: Illustration of how to add a milestone to a gantt chart [src]

You may note that by default the title color is red for milestones. If you like to change this to be instead, saybold black, you would invoke the SetColor() and SetFont() methods on the title property of milestones as in

$milestone−>title−>SetFont(FF_FONT1,FF_BOLD);$milestone−>title−>SetColor("black");

and thew result would now (not surprisingly be)

Figure 6: Modifying the milestone title color and font [src]

To modify the caption you do exactly the same but act on property 'caption' instead of 'title', i.e.

$milestone−>caption−>SetFont(FF_FONT1,FF_BOLD);$milestone−>caption−>SetColor("black");

It is worth noting that you modify the bar title and caption the exact same way by acting on the 'title' and'caption' property for the bars.

10/07/2002 01:19:24 AM 111

Page 116: Jpgraph Manual

9.9.4 Vertical line

The final object you may add to a Gantt chart is simple, but quite useful, a straight vertical line extending overthe whole plot height. This could for example be used to illustrate different phases in a project. You create aline object by a call to GanttVLine()

The full signature for GanttVLine() is

function GanttVLine($aDate,$aTitle,$aColor,$aWeight,$aStyle)

$aDate Date for the milestone

$aTitle Title for the line. The title is displayed at the bottom of the line

$aColor Color for the line

$aWeight Line width

$aStyle Line style,"dashed", "dotted" and so onValid creations of lines are for example

$vline = new GanttVLine("2001−12−24");

$vline = new GanttVLine("2001−12−24","Phase 1");

$vline = new GanttVLine("2001−12−24","Phase 1","darkred");

$vline = new GanttVLine("2001−12−24","Phase 1","darkred",5);

$vline = new GanttVLine("2001−12−24","Phase1","darkred",5,"dotted");

To add the line to the graph you just have to call GanttGraph::Add() as with milestones and bars. Let'sillustrate the use of vertical lines by adding a line to the previous example.

$vline = new GanttVLine("2001−12−24","Phase 1");$graph−>Add($vline);

10/07/2002 01:19:24 AM 112

Page 117: Jpgraph Manual

and the example (See 7) now becomes

Figure 7: Adding a vertical line with a title to the Gantt chart [src]

From the above figure you can see that by default the line is drawn at the beginning of the day of the specifieddate and in a 'dashed' style. This can (of course!) be modified so that the line is drawn/aligned anywhere in thespecified day. You modify this by invoking the method SetDayOffset() with an argument specifying thefraction of the day where you want the line positioned.

If you, for example, want to display the line in the middle of the day just add the line

$vline−>SetDayOffset(0.5);

to the previous code and the result will be

Figure 8: Modifying the position of the line within the day [src]

As usual you may modify the font, size and color by invoking the appropriate method (SetFont(), SetColor())on the 'title' property of lines.

10/07/2002 01:19:24 AM 113

Page 118: Jpgraph Manual

9.9.5 Adding markers to a gantt bar

You can easily add a variety of masrkers both to the start and end of the gantt bar. They could for example beused as an alternate way to illustrate important milestones or anticipated deliveries.

The left and right markers are accessed through the two properties 'leftMark' and 'rightMark'. They are bothinstances of the general 'PlotMark' class which is also used for the milestones (and in line graphs). The'PlotMark' class supports several different styles, for example, diamond (the default for milestones), filled andunfilled circles, squares, stares, and so on. Please refer to the reference section for a complete listing.

Let's illustrate this by adding a right marker to the previous example. We will use a style of a filled (red) circlewith a white title, say, "M5". In order to accomplish this we must augument the previous example with thefollowing lines:

$activity−>rightMark−>Show(); $activity−>rightMark−>title−>Set("M5");$activity−>rightMark−>SetType(MARK_FILLEDCIRCLE);$activity−>rightMark−>SetWidth(10);$activity−>rightMark−>SetColor("red");$activity−>rightMark−>SetFillColor("red");$activity−>rightMark−>title−>SetFont(FF_ARIAL,FS_BOLD,12);$activity−>rightMark−>title−>SetColor("white");

This might seem like a lot of lines but this is as complicated as it possible can get. As an illustration I havechanged more or less everything that is changeable. I changed the defult font, font−color, fill−color,frame−color and width of marker. The two lines only really necessary are the first two, showing the mark andsetting a title. You could get away with using default values for the rest of the properties.

The resulting image can be seen in Figure 9 below.

Figure 9: Adding a right marker to a bar. [src]

10/07/2002 01:19:24 AM 114

Page 119: Jpgraph Manual

I have deliberately introduced a "strangeness" here. If you compare the two previous examples you can seethat the last example is larger than the previous one. Why?

The explanation is simple if you remember that the height of bars are sized relative to the horizontal spacing.The horizontal spacing are based on the highest single bar including title size and, here come the explanation,marker size. The horizontal spacing has grown since the minimum height is now based on 10 points(=theheight of the mark). The bar still occupy the same percentage of the height so it seems to have grown.

If this behaviour is unwanted it is always possible to specify an absolute size for the bar heigh, say 8 pixels,with a call

$activity−>SetHeight(8);

and achive the result in Figure 10 below.

Figure 10: Specifying an absolute size for the height of the bar. [src]

It is worth noting that the height reserved for each bar is still the same since we haven't changed the height ofthe marker and the reserved space is the maximum height used by any bar.

9.9.6 Adjusting the minimum distance between bars

Let's see what happens if we set the height of each bar to be 100% of the reserved height by adding anotheractivity/bar below the first one and set the height of each bar to 100% by adding the lines (I omit the addedlines to add another bar since they are just a copy of the first bar)

$activity−>SetHeight(1.0);$activity2−>SetHeight(1.0);

to the previous example. (Note that a value in the range [0..1] is interpretated as the fraction of the reserved

10/07/2002 01:19:24 AM 115

Page 120: Jpgraph Manual

height while a value > 1 is interpretated as the absolute size in pizels.)

Figure 11: Setting the height for each bar to 100% [src]

Aha.. What we are trying to do doesn't really make sence. Since we have specified that the bar will alwaysoccupy 100% of the available reserved with there will be no distance between the bars. So what if we specifythe bar as 10 pixel absolute by changing the lines to

$activity−>SetHeight(10);$activity2−>SetHeight(10);

we instead get

Figure 12: Setting both bars height to 10 pixels [src]

So what can we actually do? Well if you remember the reserved height for each bar is the maximum height ofall bars including titles. This guarantees that no two bars will ever overlap. To guarantee that titles don't end

10/07/2002 01:19:24 AM 116

Page 121: Jpgraph Manual

up too close together there is a Vertical Label Margin which basically specifies some extra "air" in betweenthe titles. The amount of air is specified in percent of the title height. To set the margin you use

GanttGraph::SetLabelVMarginFactor($aMargin)

As an example let's set that margin in the previous example to 0 and see what happens.

Figure 13: Setting the vertical label margin to 0% [src]

As you would perhaps expect the two bars just barely touches now since there are no extra margin added. Ifthe two bars hadn't had the extra right marker it would have looked very compressed.

By default the vertical margin is set to 40%.

9.10 Formatting the scale headers

The scale headers allow you to view up to four different scales at the same time. The four basic scales are:

Day scale• Week scale• Month scale• Year scale•

These scale header are all accessed through the graph instance variables 'scale' as in

$graph−>scale−>week

or

$graph−>scale−>day

10/07/2002 01:19:24 AM 117

Page 122: Jpgraph Manual

. All these headers share the following properties.

Show()

Determine if the scale should be shown or not

SetFont()

Font for text in header

SetFontColor()

Specify the color of the header text

SetStyle()

Specify what date format should be used, for example in the week scale it is possible to show eitherweek number, the start date of the week and so on.

SetBackgroundColor()

As it says, the background color for the header

SetFrameWeight()

The line weight of the box around the scale

SetFrameColor()

The line color for the frame

10/07/2002 01:19:24 AM 118

Page 123: Jpgraph Manual

SetTitleVertMargin()

The margin, in percent, below and above the title text

In addition to these methods each scale also has the property 'grid' which determines the appearance ofgridlines for that specific scale. You may modify the appearance of gridliens by the "normal" line methods,i.e. SetColor(),SetWeight() SetStyle() and Show(). So for example to set the week gridline red you would use

$graph−>scale−>week−>grid−>SetColor("red");

Each of the scales also have some specific formatting possibilities as described below.

9.10.1 Day scale

Days are shown as "one letter boxes". The extra formatting possibilities you have for days is the possibility tospecify a different color for the weekend background and for the Sunday.

SetWeekendColor()

Set the background color for weekends. (Defaults to light gray)

SetSundayFontColor()

The Sunday font color. (Defaults to red)

In addition to this there is also a possibility to choose whether or not the weekend background should beextended vertically down over the plotare. By default it is. Since that is a property more of the whole plot youmodify this behaviour with a call to the method

UseWeekendBackground()

of the scale, e.g.

$graph−>scale−>UseWeekendBackground(false);

9.10.2 Week scale

Week scales, if enabled, by default shows the week number in range 1 to 53 (as defined by ISO−8601, see thereference section).

10/07/2002 01:19:24 AM 119

Page 124: Jpgraph Manual

It might be worth pointing out here that the week number calculation is carried out within JpGraph and doesnot rely on the underlying OS date libraries. This makes the behaviour consistent over several OS:s (at leastM$ Windows does not comply to ISO−8601 or supply any way of doing this through the normal libraries, e.g.strftime())

You may modify the week behaviour in three ways. You can specify (with SetStyle()) a different date formatusing the constants

WEEKSTYLE_WNBR

Show weeknumber To further modify the formatting of the actual week number you can optionallysupply a format string witha call to

SetLabelFormatString()

The format of the string should be a standard sprintf() syntax expecting an integer (the weeknumber).By default a 'W' is prefixed to the number.

WEEKSTYLE_FIRSTDAY

Show date of first day in week.

9.10.3 Month scale

For month scale you can use the SetStyle() method to choose between a variety of formats.

MONTHSTYLE_SHORTNAME

Display the month name in its locale specific short form, i.e Jan, Feb etc

MONTHSTYLE_SHORTNAMEYEAR2

Display the month name in its locale specific short form together with a 2 digit year , i.e Jan '01, Feb'01 etc

MONTHSTYLE_SHORTNAMEYEAR4

10/07/2002 01:19:24 AM 120

Page 125: Jpgraph Manual

Display the month name in its locale specific short form together with a 4 digit year , i.e Jan 2001,Feb 2001 etc

MONTHSTYLE_LONGNAME

Display the month name in its locale specific long name, i.e. January, February

MONTHSTYLE_LONGNAMEYEAR2

Display the month name in its locale specific long name together with a 2 digit year , i.e January '01,February '01 etc

MONTHSTYLE_LONGNAMEYEAR4

Display the month name in its locale specific long name together with a 4 digit year , i.e January2001, February 2001 etc

9.10.4 Year scale

Year scale has no extra formatting possibilities. (Simply because I couldn't come up with any usefullmodification of a simple year. If you have any suggestion of fancy formatting you think could be usefullplease drop me a note and I have something to do for the next version)

9.11 More formatting for bars

This section shows some further modification you might do to activity bars.

9.11.1 Adding caption to bars

Caption for bars are placed at the far right side of the bars. They can for example be used to indicate theresources assigned to a task, the duration of the task or the progress of the activity.

Caption text for a bar is specified either when creating a bar or later by accessing the 'caption' property ofbars. So the two lines

$activity = new GanttBar(0,"Activity1","2001−11−21","2001−12−20","[BS,ER]")

and

10/07/2002 01:19:24 AM 121

Page 126: Jpgraph Manual

$activity−>caption−>Set("[BS,ER]");

are both ways of specifying the caption "[BS,ER]" for the activity. Since activity is a standard JpGraph textobject you can easiliy modify font, color and size with calls to SetFont() and SetColor(), (e.g.

$activity−>caption−>SetFont(FF_ARIAL,FF_BOLD,9);

The figure below illustrates the use of caption

Figure 14: Illustration of the use of captions [src]

9.11.2 Adding progress indicators to bars

To indicate the progress of a specific activity it is also possible to add a progress indicator to each bar. Thisprogress indicator consists of a smaller bar within the bar. By default this progress bar is black and 70% of theheight of the bar. These parameter can (of course) all be changed.

The properties for the progress indicator are accessed through the 'progress' property and it's methods.

To set the progress for a specific activity you only specify the percent as a fraction. As in

$activity−>progress−>Set(0.4)

In Figure 15 the previous example is modified to indicate the progress of each activity by the default progressindicator. A solid bar. To make it clearer I have also modified the caption to reflect the displayed progress. (Atthe same time I slightly modified the scale headers just for fun).

10/07/2002 01:19:24 AM 122

Page 127: Jpgraph Manual

Figure 15: Adding progress indicators. [src]

To specify a different format for the progress you use the SetPattern() method as in

$activity−>progress−>SetPattern(BAND_RDIAG,"blue");

In the reference section you can see the exact parameters and all available methods.

Figure 16: Changing the style of the progress indicators. [src]

9.12 More general Gantt formatting

In this section we will show a few more way by which you may customize the gantt chart itself. This includes

Adding a table title (not to be confused with the graph title)• Adjusting appearance of the various lines in the bar chart•

9.12.1 Adding a table title

The (default) white area in the top left of the gantt table may have a title. This is accessed by the 'tableTitle'property of the gantt scale. Using this is straightforward as the following lines show.

10/07/2002 01:19:24 AM 123

Page 128: Jpgraph Manual

$graph−>scale−>tableTitle−>Set("(Rev: 1.22)");$graph−>scale−>tableTitle−>SetFont(FF_FONT1,FS_BOLD);$graph−>scale−>SetTableTitleBackground("silver");

The example lines above also changes the default white background to silver. Adding these lines to theprevious example gives the following result:

Figure 17: Adding a table title. [src]

From the above example you might notice that the width of the left column (which holds all the titles) haveautomtically adjusted itself to make the table title fit.

9.12.2 Modifying the divider lines

The vertical and horizontal lines between the titles and the bars can be modified by accessing the 'divider' and'dividerh' properties of the scale. Again, this is straightforward as the following example shows:

$graph−>scale−>divider−>SetWeight(3);$graph−>scale−>divider−>SetColor("navy");$graph−>scale−>dividerh−>SetWeight(3);$graph−>scale−>dividerh−>SetColor("navy");

The effect of this is shown in Figure 18 below

10/07/2002 01:19:24 AM 124

Page 129: Jpgraph Manual

Figure 18: Modifying the dividing line [src]

9.12.3 Modifying the box around the plot

In a similair manner to the other plots in JpGraph you modify the Box round the plot with the standard graphmethod 'SetBox()' as in

$graph−>SetBox(true,"navy",3)

which will result in a thicker plot box around the area as shown below

Figure 19: Modifying the box around the plotarea [src]

Note: You might notice the slight discrepancy in design that here you use a method and in the previous cases accessed a property which you modified. This isthe unfortunate affect of over a years development of JpGraph. My own design preference has simply changed over time. For revision 2.x I plan on taking theopportunity to make things like this more conform since I have now convinced myself that this is a better design.

9.13 Advanced formatting

9.13.1 Showing only part of the graph

You can choose to only display a vertical slice of the overall Gantt chart by explicetly sepcifying a date rangewith the method GanttGraph::SetDateRange(). This will cap any bars to only be displayed in between the start

10/07/2002 01:19:24 AM 125

Page 130: Jpgraph Manual

and end date given as paramneters. For exampel specifying

$graph−>SetDateRange("2001−12−20","2002−01−20");

will show the part of the Gantt chart between the 20 Dec 2001 and 20 of January 2002. Please note that theformat depends on the locale setting.

9.13.2 Specifying start day of week

You can set the week start day with a call to GanttScale::SetWeekStart(). This method takes an integer [0,6]as input which represents the startday of the week, 0 means Sunday, 1 Monday, 2 Tuesday and so on. Thedefault is to start the week on Monday.

9.14 Localizing

Depending on your installation of PHP you might have support for several locales. By default the locale is setup to use the default locale on the server.

To specifically set a locale you specify the wanted locale with a locale string (ala standard PHP), for exampelamerican english is pecified with the string 'EN_US', brittish english with 'EN_UK' 'nl_NL' for Dutch and soon. If your current installation does not support the specified locale an error message will be given.

$graph−>scale−>SetDateLocale("se_SE");

The result is displayed below.

Figure 20: Using swedish locale. (Can you spot the difference from English?) [src]

10/07/2002 01:19:24 AM 126

Page 131: Jpgraph Manual

10 Miscellanies features

10.1 Anti−aliasing in JpGraph

From version 1.2 JpGraph supports drawing of anti−aliased lines. There are a few caveats in order to use thiswhich is discussed in this section.

Sidebar Note that anti−alising will not be used for either horizontal, vertical or 45 degree lines since they are by their nature are sampled at adequate rate.

10.1.1 Enabling anti−aliased lines

Anti−aliased lines are enabled by calling the method SetAntiAliasing() in the Image class in the script whereyou want to use anti−aliasing.

The anti−aliasing for lines works by "smoothing" out the edges on the line by using a progressive scale ofcolors interpolated between the background color and the line color.

Sidenote: The algorithm used for anti−aliasing of lines is quite simple. It would be possible to achieve even better result by doing some real 2D signalprocessing. However, doing real time 2D signal processing on a HTTP server would be madness so I deliberately kept it simple. To achieve best visual resultalways use a dark line color on a light background.

An example will show that this, quite simple algorithm, gives a reasonable good result. The figures belowshows a radar plot with and without anti−aliasing.

Figure 1: Spiderplot without anti−aliasing [src] Figure 2: Spiderplot with anti−aliasing [src]

One thing you need to keep in mind when deciding to use anti−aliasing is that it could have potentially adramatic effect on the time it takes to generate the image. Line drawing with anti−aliasing turned on isroughly 8 times slower than the normal line drawing so treat this feature wisely.

Furthermore there are a couple of "gotchas" you should be aware of when using anti−aliasing.

Anti−aliased lines uses up more of the available color−palette. The exact number of colors used isdependent on the line−angle, a near horizontal or near vertical line uses more colors (number of lineswith different angles uses more colors). Hence it might not be possible to use anti−aliasing withcolor−gradient fill since the number of available colors in the palette might not be enough. A normal

1.

10/07/2002 01:19:24 AM 127

Page 132: Jpgraph Manual

palette can keep around 256 colors. This means that you are advised to use a truecolor image whenusing anti−aliasing.Anti−aliasing does not work very well together with background images since it assumes a the samesolid color on each side of the line. Doing a more advanced anti−aliasing algorithm would simple taketo much processing power.

2.

Anti−aliased lines will ignore the line width specified. They will always have a width of roughly 1.3.

10.2 Rotating the graphs

JpGraph provide the possibility for you to rotate the generated graph an arbitrary angle. This will only affectthe actual graph (axis, axis titles, labels and so on) and not fixed elements on the graph like title or footer.

Rotation is probably most used to rotate a graph 90 degrees, for example a bar graph to get the effect ofhorizontal bars.

Performance note: Adding a rotation transformation will make the graph generation slightly slower since each point of the graph as to go through atransformation step before being stroked on to the image. JpGraph optimises this by using a pre−calculated transformation matrice and also optimises thespecial case 90 degrees.

By default the center of the rotation will be the center of the plot area, which may or may not coincide withthe center of the entire image.

To control the rotation you use the two methods

Graph::image::SetAngle(), Specify rotation angle in degrees.• Graph::image::SetCenter(), Specify center of rotation in absolute image pixels•

For example

$graph−>image−>SetAngle(45);

There is actually a third method that you could use, adding a translation to the graph after the rotation. Sincethis probably a very little used method we don't discuss it further but refer the reader to the class referenceinstead Graph:image::SetTranslation()

When you rotate an image you should be aware of that the individual labels on the axis are not rotated. Thedesign decision behind this isa) Bit mapped font can't be rotatedb) Maintain readability

Please remember that you may still rotate the labels by calling the Axis::SetLabelAngle() method.

Since the anchor point for labels is by default the optimum for graph at 0 degree you might want to adjust theanchor point and alignment for the labels on the axis to get a better visual appearance on you rotated graph.This is accomplished by the method Axis::SetLabelAlign() For a detailed discussion on how to do this pleasesee the section on horizontal bar graphs, ( Working with bar plots )

10/07/2002 01:19:24 AM 128

Page 133: Jpgraph Manual

The table below shows some examples on different kinds of rotation to give you an idea of how changing theangle and rotation center may be used to generate different effects. The top left graph is the original image.The point of rotation has been marked with a red−cross in each of the images.

Figure 3: Original image [src] Figure 4: Rotated 45 degrees around center of plot area [src]

Figure 5: Rotated 90 degrees around center of plot area [src] Figure 6: Rotated 45 degrees around center of the image [src]

Figure 7: Rotated 90 degrees around center of the image [src] Figure 8: Rotated −30 degrees around the lower left point of the plot area [src]

As you can see from the images above if you rotate about any other point than the center of the plot area theplot can be placed outside the image after rotation.

Since the rotation, by design, only affects the plot area it is often most effective to use when the color of themargin is the same as the background color.

10.3 Adjusting brightness and contrast for images andbackgrounds

10/07/2002 01:19:24 AM 129

Page 134: Jpgraph Manual

It is often desirable to have a background image look a little bit "washed" out so it doesn't take theconcentration away from the actual graph. There are basically two ways of accomplish this

Prepare the image with an external images editor to adjust the level of brightnes and contrasty to adesirable level

1.

Use JpGraph:s built int adjustment for contrast, brightness and color saturation.2.

To adjust the background image call The levels for both brightness and constrast are real numbers in the range[−1, 1] You can choose to adjust for example just the background image or you might also choose to adjustthe whole image. To change the background image just use the method Graph::AdjBackgroundImage() tospecify a suitable value. Let's show some example on what we can do with this. The following example havebeen generated by using the small utility "adjimg.php" which you can find in the "utils/" directory.

Brightness=0, contrast=0, saturation = −1 (Originalimage)

Brightness=0, contrast=0, saturation = −1 (Black Whiteimage)

Brightness=0.3, contrast=−0.3, saturation=0 Brightness=0.4, contrast=−0.7, saturation=0

10/07/2002 01:19:24 AM 130

Page 135: Jpgraph Manual

Brightness=0.4, contrast=−0.7, saturation=−1 Brightness=0, contrast=0, saturation=1

10.4 Timing the generation of graphs

During development and optimization it can be very handy to have the actual time it took to generate theimage as a footnote. The following example shows the usage of this feature

Figure 9: Timing of a graph [src]

To enable this feature you can proceed in two ways.

You can either set the global define BRAND_TIMIING (in jpgraph.php) to true. This will add thetiming string to all graphs generated.

1.

.. or you can enable it for a specific graph by setting the global variable $gJpgBrandTiming as in

$gJpgBrandTiming=true;

2.

in the beginning of the script.

If you like you might also change the way the timing is formatted by setting the string defined byBRAND_TIMING_FORMAT (in jpgraph.php). This string represents a standard printf() format string.

Sidenote: JpGraph contains a utility class called JpgTimer which you can use yourself should you need ms timing of part of your own code. The API is reallysimple. The class supports multiple running timers and you start a timer simply by calling the Push() method. This will start a new timer and put it on the top

10/07/2002 01:19:24 AM 131

Page 136: Jpgraph Manual

of the timer stack. To stop the timer, pop it from the stack and return the timing value simply call Pop().

10/07/2002 01:19:24 AM 132

Page 137: Jpgraph Manual

11 Working with canvas graphsCanvas graphing is an advanced feature that comes in handy where you need to draw some more arbitrarygraphics. To give you a flavour of what you can do the following example shows an architecture overview ofJpGraph which was drawn using a canvas.

Figure 1: Example of what you can draw on a canvas [src]

Working with canvas requires more understanding of JpGraph as well as more programming and fine tuning.

10/07/2002 01:19:24 AM 133

Page 138: Jpgraph Manual

11.1 Introduction

Canvas graph is really not a graph. It a blank sheet of paper which you can use to draw arbitrary shapes andstill have access to some of the convinient features of JpGraph.

You can work with a canvas in different levels of complexity. You can for example work directly with theImage class which provides a large number of primitives for drawing but requires that you use absolute pixelcoordinates.

You can also make life a little bit easier by using a canvas scale. This lets you define your own scale on thecanvas which often makes it easier by letting you work on a grid you have specified yourself. It also makes itvery easy to re−scale you image automtically by just changing your scale. For example to half the size of youdrawing you just make the scale twice as large.

To give you some help in working with different canvas you should include the "jpgraph_canvtools.php" filewhen working on canvases. This is not strictly necessary but it will give you some nice abstraction to help youcreate your masterpieces.

As another (concrete) example on the use of a canvas the figure below is a listing of font styles available withJpGraph.

Figure 2: Another example of using a canvas to draw a number of text boxes [src]

10/07/2002 01:19:24 AM 134

Page 139: Jpgraph Manual

11.2 Creating a simple canvas

In order to create a canvas graph you need to include the file "jpgraph_canvas.php" in addition to the standard"jpgraph.php" file. You might also want to include the "jpgraph_canvtools.php" to get access to somesupporting classes that may (or not) come in handy.

Creating a canvas gives you the opportunity draw arbitrary shapes on a "white" piece of paper. Let's first showa simple exmaple were we just draw a text box. We first show you the code which we will walk through

(File: canvasex01.php)<?php// $Id: canvasex01.php,v 1.2 2002/08/27 20:09:31 aditus Exp $include "../jpgraph.php";include "../jpgraph_canvas.php";

// Setup a basic canvas we can work$g = new CanvasGraph(400,200,'auto');$g−>SetMargin(5,11,6,11);$g−>SetShadow();$g−>SetMarginColor("teal");

// We need to stroke the plotarea and margin before we add the// text since we otherwise would overwrite the text.$g−>InitFrame();

// Draw a text box in the middle$txt="This\nis\na TEXT!!!";$t = new Text($txt,200,10);$t−>SetFont(FF_ARIAL,FS_BOLD,40);

// How should the text box interpret the coordinates?$t−>Align('center','top');

// How should the paragraph be aligned?$t−>ParagraphAlign('center');

// Add a box around the text, white fill, black border and gray shadow$t−>SetBox("white","black","gray");

// Stroke the text$t−>Stroke($g−>img);

// Stroke the graph$g−>Stroke();

?>

10/07/2002 01:19:24 AM 135

Page 140: Jpgraph Manual

The example above starts by creating a (400x200) sized image. We set the margins to get a nice frame aroundthe image. For canvases the margins has no effect in the way you enter coordinates. Top left is (0,0) andbottom right (including any potential margin and shadow) is the maximum. In this case the coordinates areX:0−399, and Y:0−199

We then call the InitFrame() method which actually strokes the margin and plotarea to the graph. Sinceeverything is stroked in the order you issue the commands you must make sure that the graphical objects youwant on top is stroked last. This is different from the way you normally work with JpGraph since it queuesupp all you addition and then makes sure thay are stroked in the correct order.

We then create a Text object, setup it's properties, inculding the absolute screen position where we want thetext, and then stroke it. Her it might be a need for a closer explanation of the, perhaps misnamed, methodText::Align() This method states how the text coordinates should be interpreted , i.e when we specify(200,10) as the coordinates for the text paragraph should that be interpreted as the top left corner, bottom−leftcorner or somthing else (of the bounding box)? In the code above we have choosen to interpet theX−coordinate as beeing the center of the bounding box and the Y−coordinate as the top. Hence the text willbe aligned so that the (200,100) point iun the graph is aligned with the middle of the top line of the paragraphsbounding box.

We also specify that the lines within the paragraph should be centered with a call to Text::ParagraphAlign()Since we also choose to have a box around the text we have to make use of the method Text::SetBox() whichis used to specify the fill color, the border color and the shadow color (if you leave out shadow color or set itto '', no shadow will be used).

Now we are ready to stroke the text onto the canvas. In order to do so we must specify the basic Imagedrawing class we want to use. Without discussin this further we just state that a suitable image class canalways be found as the img property of the Graph class.

Finally we are ready to stroke the entire graph, which in effect sends the canvas back to the browser. Belowyou can see the effect of all this code

Figure 3: A simple canvas drawing with a text box in the middle [src]

10/07/2002 01:19:24 AM 136

Page 141: Jpgraph Manual

11.3 Adding lines and rectangles to a canvas

A canvas also makes a good background for using standard graphic primitives, for example circles and lines.What you first have to remember is that you are (so far) working with absolute screen coordinates andsecondly all drawing primitives are found in the Image Class accesssible as a proeprty of the Graph class. Sofor example to draw a line between coordinate (0,0) and (100,100) you would have to add the line

$graph−>img−>Line(0,0,100,100);

To your code. The following example shows some of the graphic primitives you have access to in the Imageclass

(File: canvasex02.php)<?php// $Id: canvasex02.php,v 1.1 2002/08/27 20:08:57 aditus Exp $include "../jpgraph.php";include "../jpgraph_canvas.php";

// Setup a basic canvas we can work$g = new CanvasGraph(400,200,'auto');$g−>SetMargin(5,11,6,11);$g−>SetShadow();$g−>SetMarginColor("teal");

// We need to stroke the plotarea and margin before we add the// text since we otherwise would overwrite the text.$g−>InitFrame();

// Add a black line$g−>img−>SetColor('black');$g−>img−>Line(0,0,100,100);

// .. and a circle (x,y,diameter)$g−>img−>Circle(100,100,50);

// .. and a filled circle (x,y,diameter)$g−>img−>SetColor('red');$g−>img−>FilledCircle(200,100,50);

// .. add a rectangle$g−>img−>SetColor('green');$g−>img−>FilledRectangle(10,10,50,50);

// .. add a filled rounded rectangle$g−>img−>SetColor('green');$g−>img−>FilledRoundedRectangle(300,30,350,80,10);

10/07/2002 01:19:24 AM 137

Page 142: Jpgraph Manual

// .. with a darker border$g−>img−>SetColor('darkgreen');$g−>img−>RoundedRectangle(300,30,350,80,10);

// Stroke the graph$g−>Stroke();

?>

Pleas note the way to access these routines through the img property of the Graph class. Please alos keep inmind that the coordinates are absolute.

Figure 4: Example of graphic primitives [src]

A note on GD For those of you using GD 1.xx you might notice that the large "filled circle" isn't completely filled. This is because in GD 1.xx there are nolow level primitives to fill an ellipse or circle so JpGraph tries to make the best out of a bad situation and manually fake a filled circle. For interest of speedJpGraph does not ontain a complete (for example) Bresenham−circle fill but cheats by using some existing GD routines. This is not a perfect solution and forlarge filled circles like this you get some moire−patterns in the circle. If you upgrade to GD 2.x JpGraph will be able to make full use of those new existingmethods and the fill will be perfect.

We refer you to the class refernce to find out what other graphic primitives are available for use.

11.4 Using a canvas scale

The previsou method using absolute coordinates works. But nothing more. It doesn't give you any chance toeasily scale the image (unless you manually recalulate all used coordinates) , it gets tedious to work with pixellevel resilution. Especially if you just like to draw a few basic shapes.

To help with this you can use a scale for the canvas. This lets you define a "work−space" of your choice. Youcan for example set the coordinates to be between X:0−10, Y:0−10. This makes it easier to position objects onthe canvas. This also has two additinal advantages:

If you increase the size of the canvas all objects will be automtically scale to keep their proportionswithout any changes.

You can shrink/enlarge your drawing (not the image) by just using another scale. For example if youoriginally draw the image using a (0:10, 0:10) scale and then change the scale to (0:20, 0:20) then the

10/07/2002 01:19:24 AM 138

Page 143: Jpgraph Manual

effect will be that you drawings will "shrink" to half their size.

To use this type of scaling you must make sure you include the file "jpgraph_canvtools.php" . In addition tothe scaling class their are also a couple of other utiity classes that may come in handy, especially the Shapeclass.

Using the scale is quite simple. You first instantiate a scale object passing the graph as a parameter and thenspecify the scale you want to use. This means you need to add the lines

$scale = new CanvasScale($g);$scale−>Set(0,$xmax,0,$ymax);

to your code. You can then use one of the translation methods (for example CanvasScale::Translate()) in thecanvas scale class to translate between your world coordinates and the absolute screen coordinates. Thismeans you could take the code in the example above and just add the lines, for example,

list($x1,$y1) = $this−>scale−>Translate($x1,$y1);list($x2,$y2) = $this−>scale−>Translate($x2,$y2);$g−>img−>Line($x1,$y1,$x2,$y2);

Since this pattern has to be repeated for every object that has to be drawn it makes good sense to encapsulatethis in a separate class. This is exactly why the canvas tools file also have a utility class called Shape Thisclass is mainly a wrapper around the most commonly used methods in the basic Image class (with oneimportant exception) and does all these the translation for you. Please see the class reference for a completelist of the available methodsTo set up the Shape class you instantiate it with the graphic context and the scaleyou want to use as argument as in

$shape = new Shape($g,$scale);

You are then ready to use all the methods in the shape class. Using a scale and imitating the previous examplewe would get the source shown below.

(File: canvasex03.php)<?php// $Id: canvasex03.php,v 1.1 2002/08/27 20:08:57 aditus Exp $include "../jpgraph.php";include "../jpgraph_canvas.php";include "../jpgraph_canvtools.php";

// Define work space$xmax=20;$ymax=20;

10/07/2002 01:19:24 AM 139

Page 144: Jpgraph Manual

// Setup a basic canvas we can work$g = new CanvasGraph(400,200,'auto');$g−>SetMargin(5,11,6,11);$g−>SetShadow();$g−>SetMarginColor("teal");

// We need to stroke the plotarea and margin before we add the// text since we otherwise would overwrite the text.$g−>InitFrame();

// Create a new scale$scale = new CanvasScale($g);$scale−>Set(0,$xmax,0,$ymax);

// The shape class is wrapper around the Imgae class which translates// the coordinates for us$shape = new Shape($g,$scale);$shape−>SetColor('black');

// Add a black line$shape−>SetColor('black');$shape−>Line(0,0,20,20);

// .. and a circle (x,y,diameter)$shape−>Circle(5,14,2);

// .. and a filled circle (x,y,diameter)$shape−>SetColor('red');$shape−>FilledCircle(11,8,3);

// .. add a rectangle$shape−>SetColor('green');$shape−>FilledRectangle(15,8,19,14);

// .. add a filled rounded rectangle$shape−>SetColor('green');$shape−>FilledRoundedRectangle(2,3,8,6);// .. with a darker border$shape−>SetColor('darkgreen');$shape−>RoundedRectangle(2,3,8,6);

// Stroke the graph$g−>Stroke();

10/07/2002 01:19:24 AM 140

Page 145: Jpgraph Manual

?>

The source above gives the following result

Figure 5: Drawing shapes on a canvas using a scale. [src]

If we like to make a smaller image we could just change the image size and everyting will be rescaled withoutany further code changes. SO for example making the image half the size would give the result

Figure 6: Shrinking the image to half the size is easy since the scaling will maintain the relative position of the objects [src]

If we instead wanted to keep the image size but shrink the shapes we could just make the scale twice as largewhich would result in

Figure 7: Shrinking hte graphic object by making the scale twice as large [src]

We previously mentioned that the Shape class was a wrapper around the image class with one exception. So

10/07/2002 01:19:24 AM 141

Page 146: Jpgraph Manual

what is the exception? Well, glad you asked. The exception is that it contain an additional method whichdraws an "indented rectangle". An indented rectangle is a rectangle where one of it's four corners have beenmoved into the rectangle. You create an indented rectangle by calling either Shape::IndentedRectangle() or Afew examples illustrates what this shape looks like.

Figure 8: Examples of filled indented rectangles [src]

As a final note we mention the class CanvasRectangleText Which can be used to add a text with a roundedrectangle (possibly filled) onto the canvas. The previous example where all the available fonts were drawnwere using this class. We don't describe it further but refeer the interested reader to the class reference and the'listfontsex1.php' example file.

11.5 Sample application: Drawing DB schema

As a final example we shortly discuss how the canvas type of graph was used to generate the DB schema forthe DDDA architecture.

The library php file "utils/misc/imgdbschema.php" included in the distribution contains some utility classes tomake the drawing of table schemes easier. It contains two basic classes, Class ImgDBTable and ClassImgDBSchema. The first class understand how to draw an image illustrating a single table. The second classis responsible for automaticially extract all the relevant information from a DB to draw a complete DBSchema.

Before going into this a little bit more we show what an example of this might look like.

10/07/2002 01:19:24 AM 142

Page 147: Jpgraph Manual

Figure 9: Example of using the canvas graph style together with the imgdbschema.php library to semi−automatically generate a DB schema [src]

Before going on it should be noted that the ImgDBSchema assumes that the DB can be accessed through a DBabstraction layer modelled after the abstraction layer available in the 'jpdb.php' file in the DDDA architecture.This abstraction layer assumes a MySQL database in the bottom. This specific dependency of this particularabstraction layer is the reason I have not included these classes in the generic canvas tools file.

10/07/2002 01:19:24 AM 143

Page 148: Jpgraph Manual

The second thing you should note that this library does not contain a complete automatic−layout engine butrather a very simple automatic system which, if nothing else is specified, just puts the table in a rectangulargrid. A complete graph layout engine would simple be to much to write in this context. This is also a verydifficult optimization problem and sofar not even any of the professional programs I have seen that tries thiscan achieve a satisfactory layout without manual intervention.

The critical lines int the code to generate the above graph is

$tblposadj=array($tlo,0,$tblwidth+$tlo+2,0,2*$tblwidth+$tlo+4,0,−1,16,−1,16);$dbschema = new ImgDBSchema("jpgraph_doc","FormatTblName","FormatFldName");$dbschema−>SetMargin($leftm,$topm);$dbschema−>SetTableWidth($tblwidth);$dbschema−>Stroke($this−>img,$this−>iscale,$tblposadj);

The rest of the code in the file is just to setup the canvas, add an indented rectangle to group some tables andgenerate a footer with the date and time this image was generated.

The first line instantiates a new ImgDBSCheme layout engine asking it to draw an imge for the database'jpgraph_doc'. The following two arguments specify two callback functions for formatting the text for headerand each field in a table.

The next line specify the top left margin where the drawing of the tables should be started.

The third line speicfy the width of a single table. The final lines starts the engine and draws all tables in thedatabase to the canvas. The final argument requires some further explanation. This is an offset (x,y) from thetop left corner how each individual table should be positioned. If the value is −1 indicates that the defaultvalue should be used. If this array is not specified then the tables will simple arranged line by line.

The full source code for drawing this DB schema example is shown below.

(File: dbschemaex1.php)<?php/*=======================================================================// File: DBSCHEMAEX1.PHP// Description: Draw a DB schema of the DDDA architecture// Created: 2002−08−25// Author: Johan Persson ([email protected])// Ver: $Id: dbschemaex1.php,v 1.1 2002/08/27 20:08:57 aditus Exp$//// License: This code is released under QPL// Copyright (C) 2001,2002 Johan Persson// Note: The actual drawing of the tables are semi−automatically// but you can easily adjust the individual tables position// with the 'tblposadj' array.//

10/07/2002 01:19:24 AM 144

Page 149: Jpgraph Manual

//========================================================================*/include "../jpgraph.php";include "../jpgraph_canvas.php";include "../jpgraph_canvtools.php";include "../utils/misc/imgdbschema.inc";include "../utils/jpdocgen/jpdb.php";

// Global callback to format the table header namesfunction FormatTblName($aName) {

// We want to replace any specifi references to the // 'JpGraph' project with the generic '<project>'

return str_replace('JpGraph','<project>', $aName);}

// Global callback to format each field name in the tablefunction FormatFldName($aName,$aTable) { return $aName;}

class Driver {

var $ig, $img, $iscale, $ishape; var $iymax,$ixmax; var $iwidth,$iheight;

function Driver() {

// Define Image size and coordinate grid space to work within$this−>iwidth = 600;$this−>iheight= 750;$this−>iymax = 50;$this−>ixmax = 55;

// Setup a basic canvas$this−>ig = new CanvasGraph($this−>iwidth,$this−>iheight,'auto');$this−>img = $this−>ig−>img;

// Define the scale to be used$this−>iscale = new CanvasScale($this−>ig);$this−>iscale−>Set(0,$this−>ixmax,0,$this−>iymax);$this−>ishape = new Shape($this−>ig,$this−>iscale);

// A small frame around the canvas$this−>ig−>SetMargin(2,3,2,3);

10/07/2002 01:19:24 AM 145

Page 150: Jpgraph Manual

$this−>ig−>SetMarginColor("teal");$this−>ig−>InitFrame();

}

function Run() {

$leftm=1.5; // Left margin (for table schemes)$topm=5; // Top margin (for table schemes)$tblwidth=15; // Individual table width$tlo=1; // Offset for top line

// Add the background color for the project specific tables$this−>ishape−>IndentedRectangle($leftm,$topm−1,3*$tblwidth+$tlo+6,45,

$tlo+2*$tblwidth+2,30,CORNER_BOTTOMLEFT,'lightblue');

// Stroke the tables (series of x,y offsets, If =−1 then use the // automtic positioning

$tblposadj=array($tlo,0,$tblwidth+$tlo+2,0,2*$tblwidth+$tlo+4,0,−1,16,−1,16);

$dbschema = new ImgDBSchema('jpgraph_doc','FormatTblName','FormatFldName');$dbschema−>SetMargin($leftm,$topm);$dbschema−>SetTableWidth($tblwidth);$dbschema−>Stroke($this−>img,$this−>iscale,$tblposadj);

$tt = new CanvasRectangleText();$tt−>SetFillColor('');$tt−>SetColor('');$tt−>SetFontColor('navy');

// Add explanation$tt−>SetFont(FF_ARIAL,FS_NORMAL,12);$tt−>Set('Project specific tables',$tblwidth+$leftm+3,16,15);$tt−>Stroke($this−>img,$this−>iscale);

// Add title$tt−>SetColor('');$tt−>SetFont(FF_VERDANA,FS_BOLD,26);$tt−>Set('DDDA − DB Schema',9,0.5,30);$tt−>Stroke($this−>img,$this−>iscale);

// Add a version and date$tt−>SetFillColor('yellow');$tt−>SetFont(FF_FONT1,FS_NORMAL,10);$tt−>Set("Generated: ".date("ymd

H:i",time()),1,$this−>iymax*0.96,15);

10/07/2002 01:19:24 AM 146

Page 151: Jpgraph Manual

$tt−>Stroke($this−>img,$this−>iscale);

$this−>ig−>Stroke(); }}

$driver = new Driver();$driver−>Run();

?>

10/07/2002 01:19:24 AM 147

Page 152: Jpgraph Manual

12 Utilities in JpGraphThis is a short account for the utilities shipped with JpGraph in the "utils" directory.

12.1 Under the utils/misc directory

adjimg.php Lets you adjust the contrast, brightness and saturation in a image.Usage: adjimg.php?file=nameue][turation]

gencolorchart.php Generates a color chart with all colors available in JpGraph• mkgrad.php A tool to easily generate gradient images for use as backgounds• imgdbschema.inc A set of utility classes used to easy generate DB schema reading the data straightfrom the DB. See more in the chapter Working directly on the canvas

12.2 Under the utils/jpdcgen

This directory contains all the scripts that make up the DDDA documentation architecture that is used togenerate the database based documentation architecture used for JpGraph. This is completely generic andcould be used for any PHP project which needs to combine both automatic and manual documentation.

The main entry point is jpdocedit.php

Please see the standalone documentation for DDDA.

10/07/2002 01:19:24 AM 148

Page 153: Jpgraph Manual

13 Code defines in JpGraphVarious settings in JpGraph are controilled by overall DEFINEs at the top of jpgraph.php. Most of thesedefines should not have to be changed by the regular user but left at their defualt values. Below is a completetable of all defines and their meaning.

Define, default value Comment

"CACHE_DIR","/tmp/jpgraph_cache/" The full absolute name of directory to be used as a cache. Thisdirectory must be readable and writable for PHP. Must endwith '/'

"TTF_DIR","/usr/local/fonts/ttf/" Directory for jpGraph TTF fonts. Must end with '/' Note: Thefonts must follow the naming conventions as used by thesupplied TTF fonts in JpGraph.

"USE_LIBRARY_GD2",false Specify if we should use GD 2.x or GD 1.x If you have GD 2.xinstalled it is recommended that you use it since it will give aslightly, slightly better visual apperance for arcs. If you don'thave GD2 installed this must be set to false!

'USE_TRUECOLOR',true Should the image be a truecolor image? Note 1: Can only beused with GD 2.0.2 and above. Note 2: GD 2.0.1 + PHP 4.0.6on Win32 crashes when trying to use trucolor. Truecolorsupport is to be considered alpha since GD 2.x is still notconsidered stable (especially on Win32). Note 3: MUST beenabled to get background images working with GD2 Note 4:If enabled then truetype fonts will look very ugly => You can'thave both background images and truetype fonts in the sameimage until these bugs has been fixed in GD 2.01

"USE_CACHE",false Should the cache be used at all? By setting this to false no fileswill be generated in the cache directory. The difference fromREAD_CACHE being that setting READ_CACHE to falsewill still create the image in the cache directory just not use it.By setting USE_CACHE=false no files will even be generatedin the cache directory.

"READ_CACHE",true Should we try to find an image in the cache before generatingit? Set this define to false to bypass the reading of the cacheand always regenerate the image. Note that even if reading thecache is disabled the cached will still be updated with thenewly generated image. Set also "USE_CACHE" below.

"DEFAULT_GFORMAT","auto" Deafult graphic format set to "auto" which will automticallychoose the best available format in the order png,gif,jpg (Thesupported format depends on what your PHP installationsupports)

"USE_IMAGE_ERROR_HANDLER",true Determine if the error handler should be image based or purelytext based. Image based makes it easier since the script will

10/07/2002 01:19:24 AM 149

Page 154: Jpgraph Manual

always return an image even in case of errors.

"USE_APPROX_COLORS",true If the color palette is full should JpGraph try to allocate theclosest match? If you plan on using background image orgradient fills it might be a good idea to enable this. If not youwill otherwise get an error saying that the color palette isexhausted. The drawback of using approximations is that thecolors might not be exactly what you specified. Note1: Thisdoes only apply to paletted images, not truecolor images sincethey don't have the limitations of maximum number of colors.

"LANGUAGE_CYRILLIC",false Special unicode language support

"ERR_DEPRECATED",false Should usage of deprecated functions and parameters give afatal error? (Useful to check if code is future proof.)

"BRAND_TIMING",false Should the time taken to generate each picture be branded tothe lower left in corner in each generated image? Useful forperformace measurements generating graphs

"BRAND_TIME_FORMAT","Generated in:%01.3fs"

What format should be used for the timing string?

The following defines should very rarely need to be changed

Define, default value Comment

"CACHE_FILE_GROUP","wwwadmin" What group should the cached file belong to (Set to "" will givethe default group for the "PHP−user") Please note that theApache user must be a member of the specified group sinceotherwise it is impossible for Apache to set the specified group.

"CACHE_FILE_MOD",0664 What permissions should the cached file have (Set to "" willgive the default persmissions for the "PHP−user")

"USE_BRESENHAM",false Decide if we should use the bresenham circle algorithm or thebuilt in Arc(). Bresenham gives better visual apperance ofcircles but is more CPU intensive and slower then the built inArc() function in GD. Turned off by default for speed

"JPG_DEBUG",false Enable some extra internal debug information to be shown.(Should only be changed if your first name is Johan and youhappen to know what you are doing. You have been warned.)

"_CSIM_SPECIALFILE","_csim_special_" Special file name to indicate that we only want to calc the imagemap in the call to Graph::Stroke() used internally from theGetHTMLCSIM() method.

"_CSIM_DISPLAY","_jpg_csimd" HTTP GET argument that is used with image map to indicate tothe script to just generate the image and not the full CSIMHTML page.

10/07/2002 01:19:24 AM 150