Contents Previous Next

# 9 Gantt charts

## 9.1 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.2 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 activities (possible grouped) against time.

## 9.3 Capabilities in JpGraph Gantt module

- Both automatic and manual scaling of date
- Full support for independent CSIM for both labels and activity bars
- Extremely flexible scales, possibility to use both months, weeks, days, hours and minutes as scales. Furthermore (unlike MS Project) you can have as may scales displayed at the same time as you like.
- Support for visualization of grouped activities
- Gantt 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 specified 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 easily be localized
- Full support for CSIM (or drill down graphs)
- Fully OO API which makes the API consistent and easy to learn
- ... and more

## 9.4 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 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 automatically 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 automatically 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.5 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 extensively 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.6 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 chosen. The following examples shows some possible ways of creating a new graph

- $graph=new GanttGraph()
  The size of the graph will be determined automatically, 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 automatically, 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.7 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 activities. 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 account 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 explicitly specified a height the bars will usually be added from band 0 and onwards and hence being 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 explicitly 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 automatic sizing you cant use even layout. It just doesn't make sense. Even layout is for those cases when you deliberately specify a very large image and want the bars evenly distributed using the full height.

## 9.8 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.8.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 parameter 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.8.2 Specifying start and end position for a bar

Start of bars are given as a date string. The format 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.8.3 Milestones

Milestones are similar 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 following 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.8.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.8.5 Adding markers to a gantt bar

You can easily add a variety of markers 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 augment 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 default 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 behavior 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 achieve 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.8.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 pixels.)

Figure 11: Setting the height for each bar to 100% [src]

Aha.. What we are trying to do doesn't really make sense. 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.9 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 you 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 grid lines for that specific scale. You may modify the appearance of grid lines by the "normal" line methods, i.e. SetColor(),SetWeight() SetStyle() and Show(). So for example to set the week grid line red you would use
`$graph->scale->week->grid->SetColor("red");`

Each of the scales also have some specific formatting possibilities as described below.

### 9.9.1 Minute scale

Minute scale is the lowest resolution you can use. It is often convenient to use Minute scale with "GanttScale::SetINtervall()" since by default the increment will be 1 minute. The style of minute scale can be further adjusted by the use style/i> parameters which can be one of

1. "MINUTESTYLE_MM", This will display minutes as a two digit number with a leading zero if necessary
2. "MINUTESTYLE_CUSTOM", This will let you specify you own custom minute style by making a call to HeaderProperty:: SetFormatString()

Minute scale is enabled by adding the GANTT_HMIN in the GanttGraph::ShowHeaders() call. For example as in
`$graph->ShowHeaders(GANTT_HDAY | GANTT_HHOUR | GANTT_HMIN);`

The code snippet below shows how to set up a minute scale with 30 min interval and some custom colors.

`$graph->scale->minute->SetIntervall(30);
$graph->scale->minute->SetBackgroundColor('lightyellow:1.5');
$graph->scale->minute->SetFont(FF_FONT0);
$graph->scale->minute->SetStyle(MINUTESTYLE_MM);
$graph->scale->minute->grid->SetColor('lightgray');`

### 9.9.2 Hour scale

The hour scale has more builtin formatting possibilities. The following formatting options are available

1. "HOURSTYLE_HM24", Will display the only the hour in military time 0-24 , for example 13:00
2. "HOURSTYLE_H24", Will display the hour with both hour and minute in military time 0-24, for example 13
3. "HOURSTYLE_HMAMPM", Will display the hour and minutes with a suitable am/pm postfix, for example 1:30pm
4. "HOURSTYLE_HAMPM", Will display only the hour with a suitable am/pm postfix, for example 1pm
5. "HOURSTYLE_CUSTOM", Custom defined format as specified with a call to HeaderProperty::SetFormatString()

For hours it is possible to specify the interval in either of two ways. With an integer, e.g. 6, or as time interval, e.g. "1:30" which makes the interval one and a half hour. The only restriction is that the interval must be even dividable for 24 hours since one day is the smallest possible interval to show. This means that it is allowed to use, for example 2,4,6,"1:30" or "0:45" as intervals but not 7, "2:45".

The code snippet below shows hot to set up a hour scale to with 45 minutes interval and some custom colors

`$graph->scale->hour->SetBackgroundColor('lightyellow:1.5');
$graph->scale->hour->SetFont(FF_FONT1);
$graph->scale->hour->SetStyle(HOURSTYLE_HMAMPM);
$graph->scale->hour->SetIntervall("0:45");`

The example below shows a gantt chart with the day and hour scale enabled

Figure 14: Using hour scale in the Gantt chart [src]

### 9.9.3 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 plot area. By default it is. Since that is a property more of the whole plot you modify this behavior with a call to the method
`UseWeekendBackground()`

of the scale, e.g.

`$graph->scale->UseWeekendBackground(false);`

### 9.9.4 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 behavior 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 behavior in three ways. You can specify (with SetStyle()) a different date format using the constants

- `WEEKSTYLE_WNBR`

  Show week number To further modify the formatting of the actual week number you can optionally supply a format string with a call to

  `SetLabelFormatString()`

  The format of the string should be a standard sprintf() syntax expecting an integer (the week number). By default a 'W' is prefixed to the number.

- `WEEKSTYLE_FIRSTDAY`

  Show date of first day in week.

### 9.9.5 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.9.6 Year scale

Year scale has no extra formatting possibilities. (Simply because I couldn't come up with any useful modification of a simple year. If you have any suggestion of fancy formatting you think could be useful please drop me a note and I have something to do for the next version)

## 9.10 More formatting for bars

This section shows some further modification you might do to activity bars.

### 9.10.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 easily 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 15: Illustration of the use of captions [src]

### 9.10.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 16 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 16: 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 17: Changing the style of the progress indicators. [src]

## 9.11 Grouping activities

It is common to group activities. We have used this feature in the examples of constrains. There is no special type for activity 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 triangles 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->SetType("MARK_LEFTTRIANGLE");
$groupbar->rightMark->SetType("MARK_RIGHTTRIANGLE")`

As of the current version 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.12 Using multiple columns as titles

It is often of interest not only to show one title for a gantt bar but often one wants to show, title, start date, end date, duration or effort and so on. Up until now we have, to keep things simple only shown a single title for each activity. We will now show you how you can specify an arbitrary number of columns as titles for a Gantt chart as well as adding icons in the graph columns.

First out is an example to help visualize what we will achieve

Figure 18: A Gantt chart with multiple columns [src]

To use multiple columns there is two steps. First you need to set the titles (name, color, fonts etc). Thereafter you need to add the title columns for each individual bar.

To set the columns you will have to work with the Activity information property of the scale. The following code excerpt show this

`$graph->scale->actinfo->SetColTitles(
array('Note','Task','Duration','Start','Finish'),array(30,100));`

You will notice two things. We fist specify the titles using an array. We have also specified a second array with the numbers 30 and 100. This is an optional array that specifies the minimum width of, in this case, the first two columns. By default the columns will be wide enough to hold the widesat text string in the column. However for esthetic reasons you might sometimes want to increase the minium width. This is what we have done here for the first two columns.

Furthermore you can also adjust the background colors and the style and colors of the vertical dividing grid lines. In the previous image we used the lines

`$graph->scale->actinfo->SetBackgroundColor('green:0.5@0.5');
$graph->scale->actinfo->SetFont(FF_ARIAL,FS_NORMAL,10);
$graph->scale->actinfo->vgrid->SetStyle('solid');
$graph->scale->actinfo->vgrid->SetColor('gray');`

The style for the grid lines can also be "dashed", "dotted" or "longdashed" as in other line formatting contexts within the library. You can also adjust if you would like the small "3D" effect in the titles. By default this is enabled. You can easily turn this of with a call to

`$graph->scale->actinfo->SetStyle(ACTINFO_2D);`

To adjust the colors of the vertical dividing lines in the title the method SetColor() is used as in "$graph->scale->actinfo->SetColor('navy');".

The second thins is to actually populate the columns. This is done (of course) as you add the activity bars to the graph. Previous we just used a string as the title when we wasn't using columns. By simply replacing this string with an array we specify the content of the columns.

For example to specify two column titles we just create a hypothetical Gantt bar as In the full example above we put all this in arrays to make for better coding practice since we create several bars.

In addition to ordinary text you can also add an image or any of the predefined icons available. In order to add that in a column you first create an instance of IconImage() and then specify that instance instead of the text. So in the previous code snippet if we wanted a "open folder" image in the first column we would change the lines to

`$iconopen = new IconImage(GICON_FOLDEROPEN,0.6);
$title2="";
$bar = new GanttBar(0,array($iconopen,$title2),"2003-11-23","2003-12-05");`

The available builtin icons are

- GICON_WARNINGRED
- GICON_TEXT
- GICON_ENDCONS
- GICON_MAIL
- GICON_STARTCONS
- GICON_CALC
- GICON_MAGNIFIER
- GICON_LOCK
- GICON_STOP
- GICON_WARNINGYELLOW
- GICON_FOLDEROPEN
- GICON_FOLDER
- GICON_TEXTIMPORTANT

In addition you can also use any of you own images if you specify the argument as a string, for example
`$myicon = IconImage('myicon.png');`

If you wonder, the second argument in the IconImage() call is an optional scaling factor which you can use to adjust the size of the image.

### 9.12.1 Adding a title for the columns

Precisely as before you can also have a title spanning all the columns. This title is specified with the property tableTitle of the scale. Specifying a table title will automatically adjust the height of the column titles to fit the table title. The small code snippet below shows how to add a title.
`$graph->scale->tableTitle->Set('Phase 1');
$graph->scale->tableTitle->SetFont(FF_ARIAL,FS_NORMAL,12);
$graph->scale->SetTableTitleBackground('darkgreen@0.6');
$graph->scale->tableTitle->Show(true);`

A full example of this is shown below

Figure 19: Adding a column titles stratching all title columns. [src]

### 9.12.2 Specifying CSIM entries for column titles

In exactly the same way as for a single title it is possible to specify individual CSIM targets for each of the title columns. This is accomplished by specifying an array for both the target and the alt text instead of a single string as arguments for SetCSIMTarget() The following code snippet shows how to specify that.
`$bar->title->SetCSIMTarget(array('sometarget1.html','sometarget1.html'),
array('alttext1','alttext2'));`

## 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");
$graph->scale->tableTitle->Show();`

The example lines above also changes the default white background to silver. Adding these lines to the previous example gives the following result:

Figure 20: 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 automatically 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 21 below

Figure 21: Modifying the dividing line [src]

### 9.13.3 Modifying the box around the plot

In a similar 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 22: 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 repetitive 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 sacrifices 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 appearance. 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 something similar 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 23: Using the simplified way via CreateSimple() method [src]

You may (slightly) modify the appearance 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 additional 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 available 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 constrains 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 24: 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 constrain 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 correct 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") activity is. In the example below we have added the constrains we wanted.

Figure 25: 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 constrain 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 explicitly specifying 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 parameters. For example 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 start day 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 example American English is specified with the string 'EN_US', British 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 26: Using swedish locale. (Can you spot the difference from English?) [src]

Contents Previous Next