1         Quick start on how to use JpGraph

 

1.1        Generating images with PHP

As a general rule each PHP which generates an image must be specified in a separate file which is then called on in an <IMG> tag reference. For example, the following HTML excerpt includes the image generated by the PHP script in “fig1.php”

 

. . .

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

. . .

 

The library will automatically generate the necessary headers to be sent to the browser to correctly recognize the data stream as an image of either PNG/GIF/JPEG format.

 

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

 

<?php

include ("jpgraph.php");

include ("jpgraph_line.php");

. . .
// Code that uses the jpgraph library
. . .

?>

 

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

 

1.2        A first example

 

The following simple example draws a line graph consisting of 10 Y-values

<?php

include ("jpgraph.php");

include ("jpgraph_line.php");

 

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

// Create the graph. These two calls are always required
$graph = new Graph(300,200);     
$graph->SetScale("textlin");

// Create the linear plot
$lineplot=new LinePlot($ydata);

// Add the plot to the graph

$graph->Add($lineplot);

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

Figure 1. PHP script for simple graph. (example1.php)

 

This script will generate the following graph

Figure 2. The simplest possible graph with JpGraph

You might note a few things:

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

·        By default the Y-grid is displayed in a “soft” color

·        By default the image is bordered and the margins are slightly gray.

·        By default the 0 label on the Y-axis is not displayed

 

This is a perfect fine graph but we want might to add a few things like

·        A title for the graph

·        Title for the axis

·        Increase the margins to account for the title of the axis

 

To handle this we just need to add a few more lines. (We only show the part of example 1 we changed)

 

. . .

// Increase the margins (left,right,top,bottom)
$graph->img->SetMargin(40,20,20,40);

// Add graph and axis title
$graph->title->Set(“Example 2”);

$graph->xaxis->title->Set(“X-title”);

$graph->yaxis->title->Set(“Y-title”);

 

. . .

Figure 3. Example 2. Adding a graph title and axis title

 

The graph will now look like this

 

Figure 4. A graph with added titles.

Again a couple of things should be noted

·        A default font and size is used for the text

·        The default position for the title of the graph is to be centered at the top

·        The default position for the title of the x-axis is the far right and for the y-axis centered and rotated in a 900 angle.

 

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

 

. . .

$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

. . .

 

You might by now have noticed that you apply the same methods to different objects within the graph. This is something that is a red line in this OO library. So far you have seen that a graph has a title, an x-axis, an y-axis etc. In the reference section a complete list of available objects and methods are listed. In almost most cases you will learn about a new method, like SetColor(), which you could then apply to other objects. As an example, let’s make the Y-axis red. As you might guess this is accomplished by the line:

 

. . .

$graph->yaxis->SetColor(“red”);

. . .

 

Or perhaps making the Y-axis a little bit thicker (note that this will also affect the Y-grid thickness)

 

. . .

$graph->yaxis->SetWeight(2);

. . .

 

As a final touch on this first example lets add a shadow to the frame surrounding the image. By default this is switched off. This is done by adding the line

 

. . .

$graph->SetShadow();

. . .

 

 

Figure 5. The final appearance of the graph after changing the properties of the Y-axis and adding a shadow to the frame.

1.3        Adding plot marks to line graphs

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.

 

As of JpGraph 1.3 the following marks are available:

 

·        MARK_SQUARE, A filled square

·        MARK_UTRIANGLE, A upward pointing triangle

·        MARK_DTRIANGLE, A downward pointing triangle

·        MARK_DIAMOND, A diamond shape

·        MARK_CIRCLE, A non-filled circle.

·        MARK_FILLEDCIRCLE, A filled circle

·        MARK_CROSS, A “+”-shaped cross

·        MARK_STAR, A “*” star shaped mark

·        MARK_X, A “X” shaped mark

 

Let’s add diamond marks to the graph in example 3 above. This is accomplished by adding the single line

 

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

 

The resulting graph is shown below

 

Figure 6. Line graph with plot marks in the intersections.

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.

1.4        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 step:

 

1.      Create the second plot

2.      Add it to the graph

 

To create the second plot we need some data (we could of course use the same data as in example 1 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);

. . .

 

The graph resulting from these changes will look like

 

Figure 7. Adding several plots to the same graph.

You should now note that

·        The Y-scale has changed to accommodate the larger range of Y-values for the second graph.

·        If you add several plots to the same graph they should contain the same number of data points. This is not a requirement the graph will be automatically scaled to accommodate the plot with the largest number of points but it will not look very good since one of the plot end in the middle of the graph.

 

1.5        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 a nice data array with large values

 

. . .

$y2data = array(354,200,265,99,111,91,198,225,293,251);

. . .

 

Then we need to add a second linear Y axis to the graph

 

. . .

$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 (version 1.0 of jpgraph only supports two different Y-axis and Y-scales. )

 

. . .

$lineplot2=new LinePlot($y2data);

$graph->AddY2($lineplot2);

. . .

 

To make the graph a little bit more esthetical pleasing we use different colors for the different plots and let the two different Y-axis get the same colors as the plots.

 

. . .

$lineplot2->SetColor("orange");

$lineplot2->SetWeight(2);

$graph->SetColor("orange");

. . .

 

The final graph will now look like this:

 

Figure 8. A graph with two different Y-axis and a plot for each Y-axis

 

1.6        Adding a legend to the plot

 

To know what different plots stand for it is custom to add a legend to the graph that explains what each plot represents. This is very easy to do. We only need to specify the legend text for each plot and most likely where we want the legend to be displayed. Let’s first see what we get with the default settings so we just add the text we want associated with each plot, let’s say “Plot 1” and “Plot 2”. This is done by the following two added lines

 

. . .

$lineplot->SetLegend(“Plot 1”);

$lineplot2->SetLegend(“Plot 2”);

. . .

 

If we do this we get a resulting graph as

 

Figure 9. Graph with a legend

 

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 to squeezed. (We don’t show the new values for the margins just the new method to position the legend.)

 

. . .

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

. . .

 

This will then generate the following graph

 

Figure 10. Graph with adjusted legend

The above method deserves some explanation since it might not be obvious. You specify the position as percentage 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 X-axis meaning that the distance between the right edge of the legend and the right edge of the image is 5% of the images entire width.

 

Allowed values for the X-position are [“left” ,”center”, “right”], and for the Y-position [“top”,”center”].

 

By default the text in the legend are stacked on top of each other. The other possibility to layout the legend is horizontally, i.e. the text is place horizontally after each other. You decide which way you want to have the legend by a call to the method “SetLayout($layout)” allowed values for $layout are

 

·        LEGEND_HOR

·        LEGEND_VERT

 

Lets illustrate this by changing the legend in the preceding example to use horizontal layout instead and place the legend at the bottom of the image. This is accomplished by the lines

 

. . .
$graph->img->SetMargin(40,40,20,70);
. . .

$graph->SetLegendLayout(LEGEND_HOR);

$graph->legend->Pos(0.5,0.85,"center","center");

. . .

 

Figure 11. Plot with alternative layout of legend.

1.7        Using the “Step style” to render line plots

Step style refers to an alternate way of rendering line plots by not drawin 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 crrect Y-value. This is perhaps easier demonstrated by an example.

 

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

 

. . .
$lineplot1->SetStepStyle()
. . .

 

For example, the following graph can be generated:


Figure 12. Example of lineplot with the "step style"

 

 

 


1.8        Using a 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");

. . .

 

 

The resulting graph will then be as illustrated below

 

Figure 13. Graph with a logarithmic Y2 scale.

 

If you also wanted the normal (left) Y scale to be logarithmic you would have had to change the SetScale() method call to

 

. . .

$graph->SetScale("textlog");

. . .

 

1.9        Using different combination of scales

As you saw in the previous example it is possible to use different types of scales. The supported types are

 

·        Linear scale. Both X and Y axis

·        Logarithmic scale. Both X and Y axis

·        Text scale. Only on X axis

 

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.

 

If no X-scale is given the whole numbers in consecutive order will be used as X-coordinates of the supplied Y-points as displayed in all the previous examples.

 

To specify which combination of X and Y scales you want to use a parameter is passed in the SetScale() method of the graph. The following values are allowed

 

·        “linlin”         Linear X, Linear Y

·        “linlog”       Linear X, Log Y

·        “textlin”      Text X, Linear Y

·        “textog”      Text X, Log Y

·        “loglin”       Log X, Linear Y

·        “loglog”      Log x, Log Y

 

 

So for example to specify a Text X scale and Log Y scale you will call

 

$graph->SetScale(“textlog”);

 

To specify the Y2 axis you used use “half” of the parameter string, i.e to specify a linear Y2 scale you call

 

$graph->SetY2Scale(“lin”)

 

Note. The behaviour of specifying “Text” for a Y-scale is undefined and might even blow up your server…

 

Specifying a log scale for the normal Y-axis will then generate the following image

 

Figure 14. Using different Y and Y2 scales.

 

1.10    Adding more gridlines to the plot

By default only the Y-axis have a grid 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 a grid. 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 instead wanted the gridlines to be displayed for the Y2 axis instead 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,false);

 

The resulting image will now look like

 

Figure 15. Graph with both X and Y gridlines.

Here we might show a nice feature of jpgraph. Since the Y (and Y2) scales first label (1 and 10) is quite close to the X-labels we might want to not display the first tick label. This can be done with a call

To the method SupressFirst() on the Tick object in the scale for each axis as

 

$graph->yaxis->scale->ticks->SupressFirst();

$graph->y2axis->scale->ticks->SupressFirst();

 

The graph will now look as

 

Figure 16. Graph with the first tick marks on the Y-axis suppressed.

1.11    Specifying the labels for 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. This can be done as follows.

 

. . .

$datax=array("Jan","Feb","Mar","Apr","Maj","Jun","July",”aug”,"Sep","Oct");

$graph->xaxis->SetTickLabels($datax);

. . .

 

This will then result in the following graph

 

Figure 17. Graph with specified labels for each tick of the X-axis.

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.

 

1.12    Adjusting the ticks on a text scale

As can be seen in the previous example (9) 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 every second tick label on the x-axis.

 

Specifying that we only want to print every second label on the axis is done by a call to the method

SetTextTicks() as

 

$graph->xaxis->SetTextTicks(2);

 

There is one important thing to remember with this. The $datax array must be adapted to only contain every second value as well! My reasoning behind this design decision is that when you have many Y-values, perhaps a couple of hundred, and only wants to have an X label on every 100 you shouldn’t have to specify all the labels you don’t use.

 

So now we also change $datax to

 

$datax=array("Jan","Mar","Maj","July","Sep");

 

The resulting graph will now look more esthetical pleasing as

 

Figure 18. A graph with the X-ticks adjusted to only display every second Major tick.

 

1.13    Using filled line graphs

Using a filled line plot  is not much different from using a normal line plot, in fact the only difference is 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. So for example plotting a filled “orange” line plot you would add the line

 

. . .

$lineplot->SetFillColor(“orange”);

. . .

 

If you look closely at a line-plot you will see that the normal line is still there with the color you specified with a previous call to SetColor(). IF you don’t wont this bounding line to bee visible just set it to the same color as the fill.

 

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.

1.14    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] nut 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 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 19. Example of Accumulated filled line plot.

1.15    Using elementary bar graphs

Version 1.0 of jpgraph only supports 2D vertical bar plots. Before you can use any bar plots you must make sure that you included the file “jpgraph_bar.php” in your script.

 

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

 

. . .

$datay=array(12,8,19,3,10,5);

$bplot = new BarPlot($datay);

$graph->Add($bplot);

. . .

 

This will then display a graph as

 

Figure 20. The simplest form of bar graphs

To have the bars filled with a solid color you must invoke the SetFillColor() method on the plot. So adding the line

 

$bplot->SetFillColor(“orange”);

 

will generate the following graph (no big surprise here..)

 

Figure 21. Filled bar graphs with default width.

You should note from the previous two graphs that bar graph gets automatically centred when using as text x-scale. If you were to use a linear scale they would instead start at the left edge of the X-axis.

 

1.16    Adjusting the width of the bars

By default the width of the bars are 40% of the major tick marks, i.e. the distance between two labels on the x-axis. To change this you will have to invoke the method SetWidth() with the percentage you would like to use instead, so for example having the bar graphs fill out the complete graph we specify a width of 100% (i.e. 1.0)

 

$bplot->SetWidth(1.0)

 

This would then generate the graph

 

Figure 22. Bar graphs with a width of 100%

1.17    Having the value of bars automatically displayed

To have the values of the bars displayed automatically on top of bars you use the method BarPLot::ShowValue(). To specify the exact format of the value you have to call SetValueFormat($fstring). The format of the specifying string is the same as to printf(). Some examples

 

1.18    Adding a drop shadow to the bar graphs

By invoking the method BarPlot::SetShadow() you may have a right-up shadow on each bar. This method also lets you specify the size and color of the shadow,

1.19    Using grouped bar graphs

These types of bars make is easy to group two or more bars together around each tick. The bars will be placed immediately beside each other and as a group centred on each tick mark. An example will make this clear.

 

. . .
// Some data
$data1y=array(12,8,19,3,10,5);

$data2y=array(8,2,11,7,14,4);

// Create the bar plots

$b1plot = new BarPlot($data1y);

$b1plot->SetFillColor("orange");

$b2plot = new BarPlot($data2y);

$b2plot->SetFillColor("blue");

 

// Create the grouped bar plot

$gbplot = new GroupBarPlot(array($b1plot,$b2plot));

 

// ...and add it to the graPH

$graph->Add($gbplot);
. . .

 

 

The above script will now generate the following image

 

Figure 23. Example of grouped bars

 

There is no limit on the number of plots you may group other then purely visually, it might be hard to see a couple of thousand plots grouped together…

 

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

 

So calling

 

$gbplot->SetWidth(0.9);

 

would have the affect of generating the following image

 

Figure 24. Grouped bar when the width has been specified as 90%

1.20    Using accumulated bar graphs

The final varieties of group bars you can have are accumulated bars. They work in much the same way as accumulated line plots described above. Each plot is stacked on top of each other. An example makes this clear. Let’s use the same data as in the two examples above but instead of grouping the bars we accumulate (or stack) them. The code would be very similar (actually only one line has to change)

 

. . .

$abplot = new AccBarPlot(array($b1plot,$b2plot));

. . .

 

This would then generate the following graph.

 

Figure 25. Accumulated bar plot.

As you can see each plot is stacked on top of each other.

 

1.21    Using grouped accumulated bar graphs

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

 

// Create all the 4 bar plots

$b1plot = new BarPlot($data1y);

$b1plot->SetFillColor("orange");

$b2plot = new BarPlot($data2y);

$b2plot->SetFillColor("blue");

$b3plot = new BarPlot($data3y);

$b3plot->SetFillColor("green");

$b4plot = new BarPlot($data4y);

$b4plot->SetFillColor("red");

 

// Create the accumulated bar plots

$ab1plot = new AccBarPlot(array($b1plot,$b2plot));

$ab2plot = new AccBarPlot(array($b3plot,$b4plot));

 

// Create the grouped bar plot

$gbplot = new GroupBarPlot(array($ab1plot,$ab2plot));

 

// ...and add it to the graPH

$graph->Add($gbplot);

 

The resulting plot would now look like

 

Figure 26. Combining both accumulated and grouped bar plots.

 

1.22    Using error plots

Error plots are used to visually indicate uncertain data points. This is done by for each X value give both a minimum and a maximum Y-value.

 

The following example illustrates a simple error bar. We will have 5 points, so we need 10 , so we need 10 Y-values. We also would like the error bars to be red and 2 pixels wide. All this is accomplished with (assuming the same basic graph as we used in previous examples)

 

. . .

$errdatay = array(11,9,2,4,19,26,13,19,7,12);

$errplot=new ErrorPlot($errdatay);

$errplot->SetColor("red");

$errplot->SetWeight(2);

 

$graph->Add($errplot);

. . .

 

The resulting graph would now look like

 

Figure 27. A simple example of error plot.

 

You might notice that there is one displeasing esthetical quality of this graph. The X-scale is just wide enough to just accompany the number of error bars and hence the first bar is drawn on the Y-axis and the and last bar just at the edge of the plot area. To adjust this you might call the SetCenter() method which will adjust the graph so that each X-point is centred in the middle of each major scale tick. The following example illustrates this

 

. . .

$errplot->SetCenter();
. . .

 

The resulting plot will now look more esthetic pleasing as

 

Figure 28. Centring an error graph with centred X-points within the major tick marks.

You might also note that the X-labels have also adjusted to this changed positioning, as you probably would expect.

 

 

1.23    Using line error plots

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

 

. . .

$elplot=new ErrorLinePlot($errdatay);

. . .

 

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

 

. . .

$elplot->line->SetWeight(2);

$elplot->line->SetColor(“blue”);

. . .

 

If we add that line to the previous example we will get the following graph

 

Figure 29. Example of a line error plot.

 

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

 

$errplot->SetLegend("Min/Max");

$errplot->line->SetLegend("Average");

 

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

 

Figure 30. Line error plot with legends.

 

1.24    Combining different types of plots

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

 

Figure 31. Example of plot containing both line plot and filled line plot.


 



Figure 32. Example of graph with both line plots and bars.

Note the alignment of line plot together with bar plots. Line plots are aligned with the left edge of the bar. This is a deliberate design decision since It looks (to me) less esthetical to have the line centred in the middle of the bars.

 

Tip: If you want the graph with bars and line start at the very left edge just change the x-axis to use a linear scale instead of a text scale.

1.25    Adding text to the graph

It is possible to add any number of text strings freely positioned within the image. Each text string you want to add to the graph must be added as an instance of the Text class. The positions of the strings are given as percentage of the width/height of the image. A small example will demonstrate this. Lets add a red text “This is a text” to the middle by centring it horizontal in the graph, .

 

. . .

$txt=new Text(“This is a text”);

$txt->Pos(0.5,0.5,”centered”);

$txt->SetColor(“red”);

$graph->AddText($txt);

. . .

 

That’s it! You can also adjust the size and font of the text by using the “SetFont()” method. All available text methods are described in the reference section of the manual.

 

Note. The alignment you give tells how you want the layout algorithm to treat the positions you supply.

 

It is also possible to have the text surrounded by a, possible, filled box. This is accomplished by the SetBox() method.

 

. . .

$txt->SetBox(“white”,”black”,true);

. . .

 

The above line will add a textbox with a white background, black frame and a drop shadow. This is illustrated in the figure below

 


Figure 33. Example of added text box “This is a text”.

 

 

 


1.26    Using scatter plots

 

Scatter plots are very simple; they plot a number of points specified by their X- and Y-coordinate. Each point is stroked on the image with a mark as with lineplots.

 

Even though you would normally supply X-coordinates it is still perfectly possible to use a text-scale for X-coordinates to just enumerate the points. This is especially usefull when using the “Impuls” type of scatter plot as is shown below.

 

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

 

include( “jpgraph_scatter.php”);
. . .

$sp1 = new ScatterPlot( $datay, $datax);

. . .

$graph->Add($sp1);

. . .

 

 


Figure 34. Example of scatter plot with default marks.

 


To change the apperance of the marks you can both fill tem with a specified color and you may also change their sze. Lets make the circle 10 pixels wide and filled with a red color. This is done by the lines

 

$sp1->mark->SetType(MARK_FILLEDCIRCLE);

$sp1->mark->SetFillColor(“red”);

$sp1->mark->SetWidth(10);

 

The resulting plot will now become

 

Figure 35. Example of scatter plot with modified marks.

 

For a complete list of available methods for “marks” see the reference section “Class PlotMark”.

 

1.27    Using impuls scatter plots

A final modification we can do to scatter plot is to change it to a “impuls” type plot. This is simple a scatter plot with lines from the x-axis up to the mark. This type of plot is often used in conjunction with illustration of digital signal analysis (hence the name I’ve choosen).

 

This change is accomplished by calling the SetImpuls() method as in

 

. . .
$spl->SetImpuls();

 

An example plot (where we use a text X-scale) will now look like

 

Figure 36. Example of scatter plot with Impuls style.

 

You may specify the thickness and color for the impuls line with the methods SetColor() and SetWeight() as in

 

. . .
$sp1->SetColor(“blue”);

$sp1->SetWeight(2);

 

The modified plot will then look like

 

Figure 37. Example of impuls scatter plot with blue impuls lines.

 

You may draw impuls graphs without any mark by specifying the mark type as (-1) . That way only the impuls lines will be drawn. Applying this to the previous graph will then give the result

 

. . .
$sp1->mark->SetType(-1);

 

Figure 38. Impuls scatter plot with no marks.

 

1.28    Using Pie Plots

 

Ince by now you would have a fairly good understanding on the principles you will be pleased to find that Pie plots fit quite nicely in the previous framework.

 

To Use Pie plots you must include (as usual) the base library and the pile plot extension “jpgraph_pie.php” . Let’s show the simplest possible complete code for a pie plot

 

<?php

include ("jpgraph.php");

include ("jpgraph_pie.php");

 

// Some data

$data = array(40,21,17,14,23);

 

// Create the Pie Graph. Note you may cach this by adding the

// ache file name as PieGraph(300,300,"SomCacheFileName")

$graph = new PieGraph(300,200);

$graph->SetShadow();

 

// Set A title for the plot

$graph->title->Set("Example 1 Pie plot");

$graph->title->SetFont(FF_FONT1,FS_BOLD);

 

// Create graph

$p1 = new PiePlot($data);

$graph->Add($p1);

 

// .. and finally stroke it

$graph->Stroke();

?>

 

The generated graph will the be

 

Figure 39. The simplest possible pie chart.

 

You may note a few thing

 

The simplest addition we can do is now to add some explaining legends to what the different pie-slices stand for. This is accomplished by the method Setlegends(), lets name the legends after the months as an example by adding the line:

 

$p1->SetLegends(array("Jan","Feb","Mar","Apr","May"));

 

which will the generate the graph

 

Figure 40. Pie chart with a legend.

 

1.29    Changing size and position for the pie chart

 

Changing size and position for the pie plot is accomplished by specifyin the size and position as percentage values. The size is changed by SetSize() which specifies the radius of the plot in percentage of whatever is the smallest of width and height of the image. The center of the pie is set by SetCenter(). An example of how to use these methods are given in the next section when we show how we can add several pie charts to the same graph.

 

1.30    Adding several pie chart to the same graph

 

This is done completely analogues as with adding plots as we have seen before. Just create some more Pie plots and use the Add() method to add them to the image.

One thing worth keeping in mind in regards to Legends. Since the pie graph only maintain one legend all the legend texts you add will be added to that legend. It is therefore most practical to use the same colors to mean the same things in each pie plot.

 

As an example lets take the previous image and just make four copies of the same pie plot just smaller so they fit within the image and place them evenly in a square, not much real use but it’s getting late and I run out of imagination for new data….

 

I have also take the opportunity to set the size if the legend to the smallest font ( with a call to SetFont()) so I don’t have to make the image to large to fit all the plots.

 

However, we create the four plots with the lines

 

. . .
// Create plots

$size=0.13;

$p1 = new PiePlot($data);

$p1->SetLegends(array("Jan","Feb","Mar","Apr","May"));

$p1->SetSize($size);

$p1->SetCenter(0.25,0.32);

$p1->SetFont(FF_FONT0);

$p1->title->Set("2001");

 

$p2 = new PiePlot($data);

$p2->SetSize($size);

$p2->SetCenter(0.65,0.32);

$p2->SetFont(FF_FONT0);

$p2->title->Set("2002");

 

$p3 = new PiePlot($data);

$p3->SetSize($size);

$p3->SetCenter(0.25,0.75);

$p3->SetFont(FF_FONT0);

$p3->title->Set("2003");

 

$p4 = new PiePlot($data);

$p4->SetSize($size);

$p4->SetCenter(0.65,0.75);

$p4->SetFont(FF_FONT0);

$p4->title->Set("2004");

 

$graph->Add($p1);

$graph->Add($p2);

$graph->Add($p3);

$graph->Add($p4);

 

$graph->Stroke();

 

Note: We only set the legend for the first pie plot since we assume that the other plot have the same meaning.

 

You may note that I also used the “title” property for each plot to assign each plot an individual title. (You may also add other text to the graph by creating instances of Class Text() and add them to the graph via the AddText() method in the PieGraph class.)

 

The plot will now become

 

Figure 41. Example of adding several pie plots to the same graph.

 

1.31    Additional modifications to pie plots

Just a quick note on some additional modifications you might do to pie plots.

 

·          Hiding labels. You may hide the percentage labels for a plot by a call to the method HideLabels()

·          Changing the colors of the labels by a call to SetFontColor()

·          Set precision of percentage figure with a  call to method SetPrecision()

·          Setting different colors to pie then default by calling SetSliceColors()

 

The above are all methods in the PiePlot class. For a complete overview of all the methods see the reference section.