A first (simple) example

The first example draws a line graph consisting of 10 Y-values. In this first example we show the full code. In the following examples we will only show interesting piece of the code. The full code for the examples shown below is always available by clicking the '[src]' link in the caption of the images below.
(File: example0.php)
<?php
include ("../jpgraph.php");
include (
"../jpgraph_line.php");

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

// Create the graph. These two calls are always required
$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

This is a perfect fine graph but looks a littel bit "sparse". To make it more interesting we might want to add a few things like From looking at the previous example you can see that you access all properties of JpGraph through the objects you create. Graph(), LinePlot() and so on. In general all objects you can see in the graph is accessed through a named instance.

For example the title of the graph is accessed through the 'Graph::title' property. So to specify a title string you make 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, to looka t the full source just click the [src] link in the caption. )
 

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

Again there are a couple of things you should note here

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

$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 the appropriate object. This principle is true for most methods you will learn. The methods may be applied to a variety of objects in JpGraph. So for example it might not come as a big surprise that to have the Y-axis in red you have to say:
 

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

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

$graph->yaxis->SetWidth(2)

As a final touch let's add a frame and a drop shadow around the image since this is by default turned off. This is 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]

Adding plot marks to line-plots

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

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

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

Thiw will give the graph as shown below



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

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

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

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 is represented by the 'value' property in the plot. (You can read more about the possibilities of the display value in 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.



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 the display 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 to change the displayed value with more advanced formatting such as displaying money values with "," to spearte thousends.

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 and just requires two simple step:
  1. Create the second plot
  2. Add it to the gaph
To create the second plot we need some data (we could of course use the same data as for the first plot but then 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 - not the 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

Adding a second Y-scale

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

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

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

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

and finally we create a new line plot and add that to the second Y-axis. Note that we here use a new method, AddY2(), since we want this plot to be added to the second Y-axis. Note that JpGraph will only support two different Y-axis. This is not considered a limitation since using more than two scales in the same graph would make 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 let the two different Y-axis get the same colors as the plots.

The resulting graph is shown below. source)



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

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 is noramlly 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. SO to 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



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 legend texts 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 big enough 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 also enlarge 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 the position as a fraction of the overall width and height of the entire image. This makes it possible for you to resize the image within disturbing the relative position of the legend. We will later see that the same method is 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 be relative to. In the example above we have specified "right" edge on the legend for the for the horizontal positioning 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 you had specified "left" the the legends left edge would be positioned 5 % of hte image width from the image left side.

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



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

Using the step-style to render line plots

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

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



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

Using logarithmic scale

Using a logarithmic scale requires you to include the logarithmic add on module in "jpgraph_log.php". So you must have the line
 
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 the previous example a logarithmic scale. This is done by the line
 

$graph->SetY2Scale("log");

This will then give the following result



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

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



Figure 14: 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, scatter plots as well. Even radar plots supports the use of logarithmic plots. The following example shows how to use a logarithmic scale for a bar graph.



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

More on scales

As you saw in the previous example it is possible to use different types of scales. In JpGraph you can use the following scales Any combination of these may be used. Linear and logarithmic scales are pretty straightforward. The text scale might deserve some explanation. The easiest way to think of the text scale is as a linear scale consisting of only natural numbers, i.e. 0,1,2,3,4,... . This scale is used when you just have a number of Y-values you want to plot in a consecutive order and don't care about the X-values. For the above example it will also work fine to use a linear X-scale (try it!). However, the scale is now treated as consisting or real numbers so the autoscaling, depending on the size of the image an the number of data points, might decide to display other labels then the natural numbers., i.e. a label might be 2.5 say. This is not going to happen if you use a text scale.

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.

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 only specify "half" of the string in the previous examples. So to set a logarithmic Y2 scale you will call
 

$graph->SetY2Scale("log");

Adjusting the gridlines in the plot

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

The grid is modified by accessing the xgrid (or ygrid) component of the graph. So to disply minor grid lines for 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 determines whether 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 becomes difficult to read for a viewer.

We can also enable the X-gridlines with the call
 

$graph->xgrid->Show(true)

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

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



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

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

Specifying text labels for the X-axis

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

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

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

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

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

$a $gDateLocale->GetShortMonth();
$graph->xaxis->SetTickLabels($a);

This will, now result in the image displayed below



Figure 17: Specifying text labels for the X-axis [src]

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

Adjusting the ticks on a text scale

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

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



Figure 18: Just printing every second label on the X-axis [src]

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

Which would then result in the image below



Figure 19: Rotating the X-labels 90 degrees [src]

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

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 that you must call the method SetFillColor() on a normal line plot. This will then fill the area under the line graph with the chosen color.

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



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

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

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

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

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



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

Using accumulated line graphs

Accumulated line graphs are line graphs that are "stacked" on top of each other. That is, the values in the supplied data for the Y-axis is not the absolute value but rather the relative value from graph below. For example if you have two line graphs with three points each, say [3,7,5] and [6,9,7]. The first graph will be plotted on the absolute Y-values [3,7,5] the second plot will be plotted at [3+6, 7+9, 5+7], hence the values of the 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 an accumulated 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");
$p3->SetFillColor("green");

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



Figure 22: Accumulated filled line graph [src]