Contents Previous Next

# 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 is that you have a working knowledge of PHP and have a basic understanding of JpGraph, most likely you should have read the JpGraph documentation.

This tutorial specifically will not teach you how to install PHP, Apache, TTF fonts, the GD library or any other infrastructure that you need to make JpGraph work.

## 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 this tutorial. It is always the exact code that generated the image that is shown and not a hand made copy. The PHP source is syntax highlighted to make it easier to follow. The actual file name appears for the code can always be found in the first line of the displayed source.

Sometimes (to save space) the full source is not included in the running text. For example if a new example is just a very minor modification to a previous example. In that case I just show the difference. For all images in this tutorial the full source can always 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 full source 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.

## 9.4 Capabilities in JpGraph Gantt module

- Both automatic and manual scaling of date
- Full support for independent CSIM for both labels and activity bars
- Support for visualization of grouped activities
- Gant charts can be automatically sized according to the number of bars and scale used. This means you 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
- Visualization of constrains between activities, start-to-start, start-to-end, end-to-start and end-to-end
- 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 been accomplished
- 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 simplest possible 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)
`<?php
include ( "../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();
?>
`
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), a title, start and end date.
- If you don't specify a size for the image it will be automtically decided based on the min and max dates 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 a month scale and finally we will change the color of the bar.

All that is taken care of in the code below.

(File: ganttex01.php)
`<?php
include ( "../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);
// 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 example wanted the full 4 digit year in the month header all you have to change is use the constant MONTHSTYLE_SHORTNAMEYEAR2 in the code above to MONTHSTYLE_SHORTNAMEYEAR4
- You 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 text on 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.

1. On the left side there is the activity title column.
2. On the top there is the scale headers (up to four headers may be displayed)
3. The actual plot area where all the Gantt bars and markers go
4. The margin area, where for example the titles are shown

Since a Gantt chart inherits all the usual properties of a JpGraph Graph() you have the access to the same method to formatting the image as before. For example to have a shadow around the image you call Graph::SetShadow() and to set the margin color you can use Graph::SetMarginColor(). Please refer to the reference 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 of the 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

All these objects may be extensivly modified in terms of formatting. You can specify color (both fill- and frame color), size, titles, style and patterns and so on. All these objects comes with (in my mind) sensible default so you don't have to specify a lot of parameters. But if you need a fine grain control or if you disagree with 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 for ordinary 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 and fonts 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 be generated inline.
- $graph=new GanttGraph(-1,-1,"auto")
  The size of the graph will be determined automtically, caching will be used (the name will be based on 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 a timeout 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, otherwise nothing will happen.

Since GanttGraph() inherits all the methods (that make sense for GanttGraph) from Graph you can specify shadow, 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 is specified as a date, e.g. "2001-06-23", and the vertical positions are specified as a number [0,1,2,3,...]. This vertical number indicates the position from the top where the object should be placed. To understand this you might imagine a number of "invisible" horizontal bands with a certain height. If you specify 0 as the vertical position the bar will be placed in the first band, specify 3 and the bar will be placed in the fourth band and so on.

It is perfectly legal, and perhaps even desirable to leave "gaps" when laying out bands to group related activiies. So, for example you could have three activities/bars at positions 1,2,3 and then another 2 bars at position 6,7 leaving band 0,4,5 empty.

All these "invisible bands" have the same height (equspaced). The height of each band is automatically determined and depends on both the method of layout ( as specified by (GanttChart::SetLayout()) and the individual 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 the height (+ a margin) of the highest gantt bar. The height calculation of each bar takes into accout both the actual bar, the title, and any left- right-marks (more about that later) that may be present. The name "fromtop" refers to that when you have explicetly specified a height the bars will usually be added from band 0 and onwards and hence beeing added from the top. (This might leave empty space at 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 available height in the gantt chart and no consideration is taken of the individual bars heights. Note that if you use automtic sizing you cant use even layout. It just doesn't make sence. Even layout is for those cases when you deliberately specify a very large image and whant the bars evenly distributed using the full height.

## 9.9 Gantt bars

The most common of all object in a Gantt chart is of course the activity bar (GanttBar()). In terms of formatting this object has a very large flexibility. The full signature for the GanttBar constructor is
`function GanttBar ($aVPos,$aTitle, $aStart,$aEnd,$aCaption ,$aHeight)`

`<?php $aVPos` |  | The vertical position for the bar, [0..n]
`<?php $aTitle` |  | Title for the activity
`<?php $aStart` |  | Start date for the activity given as string, e.g "2001-09-22"
`<?php $aEnd` |  | End date for activity given as either a date (a string) or as the duration (in days) of the activity, e.g both "2001-10-15" and 20.5 are valid inputs
`<?php $aCaption` |  | Text string (caption) to appear at the end (right side) of the bar
`<?php $aHeight` |  | Height of bar given as either a value in range [0,1] in which case this is interpretated as what fraction of the vertical position should the bar occupy. The height can also be given in absolute 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' activity to 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.

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 date strings 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 for the 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.

### 9.9.3 Milestones

Milestones are similair to bars but have no end date since milestones just apply to one single date. Milestones are created much the same way as activities but using method MileStone() instead.

The full signature for milestones are

`function MileStone ($aVPos,$aTitle, $aDate, $aCaption)`

`<?php $aVPos` |  | The vertical position for the bar, [0..n]
`<?php $aTitle` |  | Title for the activity
`<?php $aDate` |  | Date for the milestone
`<?php $aCaption` |  | Text to the right of the milestone

Valid milestones are for example

- `$milestone = new MileStone (3,"Code complete","2001-12-01");`

- `$milestone = new MileStone (3,"Code complete","2001-12-01", "(2001-12-01)");`

By default milestones are rendered as a filled "Diamond" shape. This may be optionally modified. The actual shape is specified by the 'mark' property of milestone which is an instance of the PlotMark() class (same class responsible 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 of code which result in Figure 5 shown below.

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, say bold 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.

### 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 over the whole plot height. This could for example be used to illustrate different phases in a project. You create a line object by a call to GanttVLine()

The full signature for GanttVLine() is

`function GanttVLine ($aDate,$aTitle, $aColor, $aWeight, $aStyle)`

`<?php $aDate` |  | Date for the milestone
`<?php $aTitle` |  | Title for the line. The title is displayed at the bottom of the line
`<?php $aColor` |  | Color for the line
`<?php $aWeight` |  | Line width
`<?php $aStyle` |  | Line style,"dashed", "dotted" and so on

Valid 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","Phase 1", "darkred",5,"dotted" );`

To add the line to the graph you just have to call GanttGraph::Add() as with milestones and bars. Let's illustrate the use of vertical lines by adding a line to the previous example.
`$vline = new GanttVLine ("2001-12-24","Phase 1");
$graph->Add( $vline);
`

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 specified date and in a 'dashed' style. This can (of course!) be modified so that the line is drawn/aligned anywhere in the specified day. You modify this by invoking the method SetDayOffset() with an argument specifying the fraction 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.

### 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 be used 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 both instances 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 and unfilled 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) circle with a white title, say, "M5". In order to accomplish this we must augument the previous example with the following 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 have changed 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 and setting 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]

I have deliberately introduced a "strangeness" here. If you compare the two previous examples you can see that 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(=the height 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 of the 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 another activity/bar below the first one and set the height of each bar to 100% by adding the lines (I omit the added lines 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 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 always occupy 100% of the available reserved with there will be no distance between the bars. So what if we specify the 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 of all bars including titles. This guarantees that no two bars will ever overlap. To guarantee that titles don't end up too close together there is a Vertical Label Margin which basically specifies some extra "air" in between the 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. If the 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

You can choose what scale to include and exclude by using the SetScale() method. For example, for a detailed gantt you might choose to display days and weeks by specifying
`$graph ->ShowHeaders( GANTT_HWEEK | GANTT_DAY );`

If you instead wanted "the big picture" it might be enough to show year and months by specifying

`$graph ->ShowHeaders( GANTT_YEAR | GANTT_MONTH );`

You can choose freely the combination of scales that you want, but a chart must at least have one scale of course.

Once you have decided what level of details you need ou can then fine tune the exact layout/formatting of each of the enabled scales as described below.

These scale header are all accessed through the graph instance variables 'scale' as in

`$graph ->scale->week`

or

`$graph ->scale->day`

. 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 either week 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

- `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 of gridlines 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 to specify 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 be extended vertically down over the plotare. By default it is. Since that is a property more of the whole plot you modify 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 the reference section).

It might be worth pointing out here that the week number calculation is carried out within JpGraph and does not rely on the underlying OS date libraries. This makes the behaviour consistent over several OS:s (at least M$ 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 format using the constants

- `WEEKSTYLE_WNBR`

Show weeknumber To further modify the formatting of the actual week number you can optionally supply 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`

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 January 2001, February 2001 etc

### 9.10.4 Year scale

Year scale has no extra formatting possibilities. (Simply because I couldn't come up with any usefull modification of a simple year. If you have any suggestion of fancy formatting you think could be usefull please 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 the resources 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 of bars. So the two lines

`$activity = new GanttBar (0,"Activity 1", "2001-11-21", "2001-12-20", "[BS,ER]")`

and

`$activity->caption ->Set("[BS,ER]");`

are both ways of specifying the caption "[BS,ER]" for the activity. Since activity is a standard JpGraph text object 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. This progress indicator consists of a smaller bar within the bar. By default this progress bar is black and 70% of the height 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 progress indicator. A solid bar. To make it clearer I have also modified the caption to reflect the displayed progress. (At the same time I slightly modified the scale headers just for fun).

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

It is common to group activities. We have used this feature in the examples of constrains. There is no special type for actvity bars that are used to illustrate grouping. The common way of illustrating this (as have been used above) is to add "half" a triangle marker at both ends of the bar. The special provision that JpGraph does is that if you add a left or right marker of type MARK_LEFTTRIANGLE or MARK_RIGHTTRIANGLE those triangles will be drawn under the bars to give the effect as show in the examples above. In the example above we also have made the grouping bars have slightly less heigh since the end trinagles will visually "grow" the bar.

So to get the effect we want for a group bar we have to use the two lines:

`$groupbar->leftMark ->Set("MARK_LEFTTRIANGLE");
$groupbar ->rightMark->Set( "MARK_RIGHTTRIANGLE")`

As of the current verion (1.10) There is not yet any formatting support to accomplish the effect of indentation for the titles so this is accomplished by using a fixed width font and adding spaces in front of the title.

## 9.13 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.13.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.
`$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 the previous 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) have automtically adjusted itself to make the table title fit.

### 9.13.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

Figure 18: Modifying the dividing line [src]

### 9.13.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 graph method '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 is the 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 the opportunity to make things like this more conform since I have now convinced myself that this is a better design.

## 9.14 Simplifying the drawing of Gantt graphs

As we have shown in the previous examples constructing a Gantt chart consists of a number of repetetive tasks; Create the individual activity bars and add them to the graph.

Now when you have a basic understanding of how this works you are ready to appreciate a small helper method. GanttGraph::CreateSimple(). This method takes a few arrays of data which specifies you Gantt chart and then constructs this chart. By using this method you sacrifies a few adjustment possibilities for simplicity. This method is nothing magical it just takes the data for the activities,(start and end date, titles, progress, any constrains and so on) and constructs the activities and adds them to the graph.

The activities are specified in data array which for each activity have the following fields

- What row the activity should be on
- Activity type, controls the apperance. Can be one of
  1. ACTYPE_NORMAL, A standard activty bar
  2. ACTYPE_GROUP, A Grouping bar
  3. ACTYPE_MILESTONE, A milestone
- Title text
- Start date
- End date (NOT FOR Milestones!)
- Caption

So for example to create a Gantt chart consisting of two activities which are grouped and a milestone one would have to use somthing similair to the following code

`$data = array(
array(0 ,ACTYPE_GROUP , "Phase 1" , "2001-10-26" ,"2001-11-23",""),
array(1 ,ACTYPE_NORMAL , " Label 2" , "2001-10-26" ,"2001-11-13","[KJ]"),
array(2 ,ACTYPE_NORMAL , " Label 3" , "2001-11-20" ,"2001-11-22","[EP]"),
array(3 ,ACTYPE_MILESTONE ," Phase 1 Done" , "2001-11-23" ,"M2") );
// Create the basic graph
$graph = new GanttGraph ();
$graph->title-> Set("Gantt Graph using CreateSimple()");
// Setup scale
$graph->ShowHeaders( GANTT_HYEAR | GANTT_HMONTH | GANTT_HDAY | GANTT_HWEEK);
$graph->scale-> week->SetStyle(WEEKSTYLE_FIRSTDAY);
// Add the specified activities
$graph->CreateSimple( $data);
// .. and stroke the graph
$graph->Stroke();
`

This will then show up as

Figure 20: Using the simplified way via CreateSimple() method [src]

You may (slightly) modify the apperance of the simple Gantt charts by means of the methods GanttGraph::SetSimpleFont() and GanttGraph::SetSimpleStyle() But not anything else, remember that the purpose with this way of constructing graphs is to be simple. If you need full advanced control you have to construct all the activities in the "normal" way.

You can also specify constrains and progress for each bar by supplying additoinal data arrays to GanttGraph::CreateSimple().

## 9.15 Adding CSIM (Client side Image Maps) to Gantt charts

Gantt charts can have independent (different targets) hot spots in both the activities and in the associated labels for each activity.

You specify the target and the associated "Alt" text for an activity bar by calling the GanttBar::SetCSIMTarget() and GanttBar::SetCSIMAlt()

In a similar way you set the target and Alt texts for the activity title as the following code extract shows.

`$bar ->SetCSIMTarget ("http://localhost/abc/" );
$bar->SetCSIMAlt( "Alt Text for the bar");
$bar->title-> SetCSIMTarget( "http://localhost/abc");
$bar->title-> SetCSIMAlt( "Alt Text for the title");`

The above code assumes that your activity is availabel in the variable 'bar'. In the example directory there is a complete example of how to use CSIM together with Gantt charts in the "ganttcsimex1.php" file. (Please note that this example makes use of the simplified Gantt chart specification using the CreateSimple() method.

## 9.16 Adding constrains between your activities

With Gantt charts there is often the need to illustrate constrans between one or several activities. One of the most common constrain is that on activity can't start before an other activity finish.

JpGraph support visualizing the following types of constrains

- Start to End
- Start to Start
- End to Start
- End to End

An example will clarify how to specify a constrain between two activities.

Assume that we start with the Gantt schema as illustrated below

Figure 21: The original Gantt schema we wich to add constrains to [src]

We would now like to add the constrains that the activity "Label 3" cant start before activity "Label 2" has finished and that the milestone "Phase 1 done" is depending on when activity "Label 3" is done.

The principle of adding constrains is that you for each activity you want to have a constrain you have to tell to what other activity this costrain should be to. That other activity is specified by telling on what row that activity lies. Depending on what type of constrain, e.g. Start-to-End, an arrow will now connect the two activities in acorrect way.

The way to do this is to call the SetConstrain() method on the activity. In this method you specify the type of constrain as well as to what other activity this constrain should be to. If you read the class reference you can also see that you can specify the type and size of arrow used. For now we will just use the default sizes and type.

So for example to add an End-To-Start constrain between "Label 2" and "Label 3" you could write

`$bar2 ->SetConstrain (2,CONSTRAIN_ENDSTART)`

The first parameter in the call above "2" is the row of the target activity (i.e. the row where "Label 3") activty is. In the example below we have added the constrains we wanted.

Figure 22: Adding constrains to a gantt chart [src]

A note: The actual path followed by the arrow is controlled by some heuristics to make it clear what the costrain is. It has been a design decision that in order to keep the API simple the user has no further detailed controlled on the actual path followed. However, in future version the heuristics may be extended and provide some user-controllable parameters.

## 9.17 Advanced formatting

### 9.17.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 range with the method GanttGraph::SetDateRange(). This will cap any bars to only be displayed in between the start 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 the format depends on the locale setting.

### 9.17.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. The default is to start the week on Monday.

## 9.18 Localizing

Depending on your installation of PHP you might have support for several locales. By default the locale is set up 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 exampel american english is pecified with the string 'EN_US', brittish english with 'EN_UK' 'nl_NL' for Dutch and so on. 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 23: Using swedish locale. (Can you spot the difference from English?) [src]

Contents Previous Next