Contents Previous Next

6.2 Line plots

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]

6.2.1 Adding plot marks to line-plots XXX

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.

6.2.2 Displaying the values for each data point

As a final easy modification we can enable the display of the data value above each data point. The value 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.

6.2.3 Adding several plots to the same graph

What if we want to add a second plot to the graph we just produced? Well, this is quite straightforward 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

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

6.2.5 Adding a legend to the graph

With more than one plot on the same graph it is necessary to somehow indicate which plot is which. This 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 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 9: 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 10: Using a horizontal layout for the legends [src]

6.2.6 Handling null-values in lineplots

JpGraph offers two ways of handling null values (or discontinuties) in the data. You can either have a "whole" in the data or the line may be extended between the previous and next data point in the graph.

If the data value is null ("") or the special value "x" then the data point will not be plotted and will leave a gap in the line.

If the data value is "-" then the line will be drawn between the previous and next point in the data ignoring the "-" point.

The following example shows both these posibilities.



Figure 11: Handling null values in line graphs [src]

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

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

6.2.9 More on scales

As you saw in the previous example it is possible to use different types of scales. In JpGraph you can use 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 SetY2Scale("log");'; ShowCodeSnippet($t); ?>

6.2.10 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() )

6.2.11 Using filled gridlines

Another option for the gridlines is the possibility to have the area between the gridlines filled with alternating two colors. The example below illustrates this.



Figure 17: Using two alternating colors between the gridlines [src]

In the example above we have also made use of alphablending (requires GD 2.x or higher). By default the filled grid lines are disabled. To enable this style you have to call the Grid::SetFill() method.

6.2.12 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 18: 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.

6.2.13 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 19: 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 20: 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.

6.2.14 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 21: Filled line graph with plot marks [src]

Note 1. If you add multiple filled line plots to one graph make sure you add the one with the highest 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 22: Adjusting the depth of the gridlines [src]

6.2.15 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 23: Accumulated filled line graph [src]

6.2.16 Constructing smooth lineplots with Cubic Splines

If you only have access to a few data points but still want a smooth curve between those datapoints JpGraph can help you achieving that by letting you construct cubic splines. If you never have heard of cubic splines before, don't worry. You only have to supply the datapoints you know tell JpGraph how many interpolated points in total you want in the graph. JpGraph will now take care of constructing a smooth curve between all you data points. The new, smooth, curve will be made up of exactly as many interpolated points as you have specified.

To construct a spline you need both the X and Y coordinates for the known data points.

You start by constructing a new Spline instance. To get access to the Spline class you must first remember to include the file "jpgraph_regstat.php". You instantiate this class by calling it with your two known data arrays (X and Y) as follows.
 

$spline = new Spline($xdata,$ydata);

This call initilaizes the spline with the data points you have. These datapoints are also known as Cotrol points for the spline. This helper class doesn't draw any line itself. Instead it is mearly used to get a new (larger) data array which have all the interpolated values. You then use these new value in your plot. This way give you great flexibility in how you want to use this interpolated data.

Continuing the above line we now use the Spline::Get() method to get an interpolated array containing a specified number of points. So for example the line
 

list($sdatax,$sdatay) = $spline->Get(50);

Will construct the two new data arrays '$sdatax' and '$sdatay' which contains 50 data points. These two arrays are constructed from the control poin we specified when we created the '$spline' object.

You would then use these two new data array in exactly the same way as you would form ordinary dat vectors.

The following example illustrates this



Figure 24: Using spline to get a smooth curve between the control points. [src]

Note: In order to make the example more interesting we actually use two plots. First a line plot to get the smooth curve and then a standard scatter plot which is used to illustrate where the control points are.

6.2.17 Adding plot marks to a line plot

To emphasize the specific data points it is possible to add plot marks at each data point. Plot marks can be either You access the plot mark through the "mark" instance variable in the plot, as in
 
$lineplot->mark->SetColor("red");

To choose between the different plot marks you call the PlotMark::SetType() method with the correct define to choose the plot type you want to use.

The simple shape type of plot marks are

To specify an arbitrary image you use the special define In this case you must also specify a image file name and an optional scaling constant. For example as in
 
$lineplot->mark->SetTYPE(MARK_IMG,"myimage.jpg",1.5);

If you want to use one of the built-in images the following images are available. Please note that not all images are available in all possible colors. The available colors for each image is listed below.

The following shape (the first class) plot marks are available

  1. MARK_SQUARE, A filled square
  2. MARK_UTRIANGLE, A triangle pointed upwards
  3. MARK_DTRIANGLE, A triangle pointed downwards
  4. MARK_DIAMOND, A diamond
  5. MARK_CIRCLE, A circle
  6. MARK_FILLEDCIRCLE, A filled circle
  7. MARK_CROSS, A cross
  8. MARK_STAR, A star
  9. MARK_X, An 'X'
  10. MARK_FLASH, A "flash" shape
  11. MARK_IMAGE, Use the image specified with the filename and scale as the second and third argument as the mark.

For the second class (built-in images) the following table list the different images as well as what color they are available in. For the built-in images you specify the color with the second argument.

Note that some of the images are available in different sizes. The reason is that even though you can scale them by the third argument there is a visual degradation to scale an image larger than it's original size since some pixels needs to be interpolated. Reducing the size with a scale < 1.0 gives much better visual apperance.

The scaling works with both GD 1 and GD 2 but with GD 2 the quality of the scaling is much better.

Built-in images and available colors:

TypeDescriptionColors
MARK_IMG_PUSHPIN, MARK_IMG_SPUSHPIN Push-pin image 'red','blue','green','pink','orange'
MARK_IMG_LPUSHPIN A larger Push-pin image 'red','blue','green','pink','orange'
MARK_IMG_BALL, MARK_IMAGE_SBALLA round 3D rendered ball 'bluegreen','cyan','darkgray','greengray', 'gray','graypurple','green','greenblue','lightblue', 'lightred','navy','orange','purple','red','yellow'
MARK_IMAGE_MBALLA medium sized round 3D rendered ball 'blue','bluegreen','brown','cyan', 'darkgray','greengray','gray','green', 'greenblue','lightblue','lightred', 'purple','red','white','yellow'
MARK_IMAGE_LBALLA large sized round 3D rendered ball 'blue','lightblue','brown','darkgreen', 'green','purple','red','gray','yellow','silver','gray'
MARK_IMAGE_SQUAREA 3D rendered square 'bluegreen','blue','green', 'lightblue','orange','purple','red','yellow'
MARK_IMG_STARA 3D rendered star image 'bluegreen','lightblue','purple','blue','green','pink','red','yellow'
MARK_IMG_DIAMONDA 3D rendered diamond 'lightblue','darkblue','gray', 'blue','pink','purple','red','yellow'
MARK_IMG_BEVELA 3D rendered bevel style round ring 'green','purple','orange','red','yellow'
Below we give two examples of images using these features.



Figure 25: Using an arbitrary image as plot mark [src]



Figure 26: Using the built-in images [src]


Contents Previous Next