jpgraph_manual.pdf

Embed Size (px)

Citation preview

  • 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 XY 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 lineplots 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 Yscale................................................................................................31

  • JpGraph Manual6 Introducing XY plot type

    6.2.5 Adding a legend to the graph...........................................................................................326.2.6 Handling nullvalues in lineplots....................................................................................346.2.7 Using the stepstyle 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 Xaxis.............................................................................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 semifilled 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 Yaxis......................................................................................................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,Yplots........................................................................................................................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

  • JpGraph Manual7 Working with non X,Yplots

    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

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

    10.1 Antialiasing in JpGraph.............................................................................................................12710.1.1 Enabling antialiased 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

  • 1 About this manual

    1.1 Version history

    Version Date Status Who Comment

    R1.0 20021005 Released Johan Persson Added additional info, proper indexing

    D1.0 20020916 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 awkscript 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 noninteractively 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

  • 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 (QtLicense) for noncommercial (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 Offline 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 textlin, textlog, linlin, linlog, loglin and loglog 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

  • 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 yscale, it is possible to have different left and right yscale and addplots to both

    Supports, lineplots, filled lineplots, accumulated lineplots, bar plots, accumulated bar plots,grouped bar plots, error plots, line error plots, scatter plots, ganttcharts, 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 antialising 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 antialiasing Version 2.0, (Summer 2003) Based on PHP builtin GD library.

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

  • 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 website 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/chart0.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 Yscales,autoscaling, and logarithmic scales), or general flexibility, I especially needed the option of two Yscales,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 Yscale 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

  • 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

  • 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 GDlibrary 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 ("Contenttype: 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

  • 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

  • http://www.coupin.net/gdfreetype/

    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 Zendcache 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 withgdnativettf (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.

    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 GD2.1.1 directory.

    Then build PHP using a minimum of:

    withgd=/home//gd2.0.1 withfreetypedir=/use enablegdnativettf enablegdimgstrttf withjpegdir=/usr withpngdir=/usr

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

  • withxpmdir=/usr/X11R6

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

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

  • 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 bitmapped 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 tag reference. For example, the following HTML excerpt includes the image generated bythe PHP script in "fig1.php".

    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 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

  • 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

  • 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 bitmapped 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 antialiasing 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 fontpath 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

  • 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

  • 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 predefined 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

  • 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

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

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

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

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

  • 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

  • Theme 3: Water

    Theme 4: Sand

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

  • 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 reallyrealtime, 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 masterswitch 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 masterswitch 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

  • 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 cronjob

    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 antialiasing you should strongly consider usingcaching since antialiasing is quite time consuming compared to standard line drawings.

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

  • 6 Introducing XY 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 Yvalues. 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)

  • $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 Ygrid 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 Yaxis 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

  • 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("Xtitle");$graph>yaxis>title>Set("Ytitle");

    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 xaxis is the far right and for the yaxis 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

  • $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 Yaxis inred you have to say:

    $graph>yaxis>SetColor("red")

    or perhaps we also want to make the Yaxis 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 lineplots XXX

    It might sometimes be desirable to highlight the datapoints with marks in the intersection between the givenx and Ycoordinates. 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

  • 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, fillcolor 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

  • 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

  • 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 Yscale has changed to accommodate the larger range of Yvalues 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 Yscale

    As you saw in the preceding example you could add multiple plots to the same graph and Yaxis. Howeverwhat if the two plots you want to display in the graph has very different ranges. One might for example haveYvalues like above but the other might have Yvalues 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 Yaxis with a different scale and add the second plot to this Yaxisinstead. Let's take a look at how that is accomplished.

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

  • 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 Yaxis. Note that we here use a new method,AddY2(), since we want this plot to be added to the second Yaxis. Note that JpGraph will only support twodifferent Yaxis. 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 Yaxis get the same colors as the plots.

    The resulting graph is shown below. source)

    Figure 8: Adding a second Yscale 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

  • 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

  • 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 nullvalues 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

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

    6.2.7 Using the stepstyle 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 Xvalue and then avertical line from that point to the correct Yvalue. 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

  • 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 Xscale 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

  • 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 Xaxis. A typical example for this is the Xaxis for a bar plot.The labels for the text scale is ususally replaced by user supplied texts. Text scales can only be usedfor the Xaxis (it doesn't make sense for the Yscale).

    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 Yvalues youwant to plot in a consecutive order and don't care about the Xvalues. For the above example it will also workfine to use a linear Xscale (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", textscale for Xaxis, Linear scale for Yaxis "linlin", linearscale for Xaxis, Linear scale for Yaxis "linlog", linearscale for Xaxis, Logarithmic scale for Yaxi "loglog", Logarithmic scale for Xaxis, Logarithmic scale for Yaxis

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

  • "textlog", Text scale for Xaxis, Logarithmic scale for Yaxis

    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 Yaxis 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 Xgridlines 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

  • Figure 17: Enabling major and minor gridlines for Yaxis and major grid lines for the Xaxis [src]

    Note: If you think the first value of the Yaxis is to close to the first label of the Xaxis 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 Xaxis

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

    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 Xaxis 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

  • Figure 18: Specifying text labels for the Xaxis [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 nonexistent positions will have empty labels.

    6.2.12 Adjusting the ticks on a text scale

    As can be seen in the previous example the Xaxis 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 xaxis.

    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 Xaxis [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 Xaxis by 90 degrees. With the help of theSetLabelAngle()

    Which would then result in the image below

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

  • Figure 20: Rotating the Xlabels 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 Yvaluesfirst 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 frontmost 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

  • 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 Yaxis 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 Yvalues [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

  • $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 Xaxis have an textscale (it is perfectly fine to use alinear Xscale 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

  • 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 Xscale. Thebar graphs gets automatically centered between the tick marks when using as text xscale. If you were to usea linear scale they would instead start at the left edge of the Xaxis and the Xaxis 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 Xscale [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

  • 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

  • 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 Yscale [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

  • 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 (Xvalue). 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

  • // 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]

    Th