The most updated version of this document is available here. You should always use that version if possible.

Advanced Graphing Class V1.7.1



This is a graphing class for PHP 5 that supports auto scaling, XML and CSV import, multiple datasets user defined size and color, and many options for end and point styles. Read this for information on how to use it.

Please report any bugs and send any suggestions to zackbloom@gmail.com or use the form below. I really love to hear both.

Send me comments or suggestions:
Email (optional)


Examples

The Code

Download

Google Code PHPClasses.org Freshmeat

Table of contents


  1. Hello World" Graph
  2. Block point addition
  3. Properities
  4. Style options
  5. CSV, XML and MySQL data importing
  6. Inline format (easy way to make quick graphs)
  7. Bar Charts
  8. Pie Charts
  9. Function Graphing
  10. Output options
  11. Method and property refrence
  12. Development info and license

1. "Hello World" Graph:


Their are 5 steps that must be followed to insert any type of graph using any data method, the steps should be followed in order. This is the most rudimentary example and will probably not be enough for a full application.
  1. Include my class, include "graph.oo.php"; .
  2. Create the graph object, $graph = new graph(); .
  3. Add data, for this example we will use the block addition method, $graph->addPoint(5); . Make up some numbers and add 5 points.
  4. Create the graph, $graph->graph(); .
  5. Display the graph, $graph->showGraph(); .

So the full code is:
<?php
include "graph.oo.php";
$graph = new graph();
$graph->addPoint(1);
$graph->addPoint(4);
$graph->addPoint(5);
$graph->addPoint(2);
$graph->addPoint(3);
$graph->graph();
$graph->showGraph("test.png");
?>

<img src="test.png">


2. Block point addition:


Block point addition is adding points through the same method you used in the last step. In this you will create a more advanced graph in which you can specify the size and some basic options about the graph. From now on I will assume you have included my class, created the graph object and named it "$graph", you could actually name it anything, but use graph for now.

In the last step you ran the constructor with no arguments, which tells it you want to create a graph that is 400px by 200px with 10 grid lines on the X axis and 6 on the Y. Most applications require more control then that, you change those options use the constructor, which is the method that is called when you create, or construct, the graph object. The syntax of the constructor is:

$graph = new graph([[[[Width],Height],X Scale Increments],Y Scale Increments]);

You don't have to include all the arguments, but all arguments to the left of an argument you want to include must have a value, so to include the X Scale you must also include the width and height.

In this example you add data using the addPoint method, the syntax of the addPoint method is:

$graph->addPoint(dependent[[,independent],dataset]);

The addPoint method returns an ID number that can be used to delete points. If you will need to delete points you should store this value, otherwise its safe to ignore it.

Datasets


This class allows for an unlimited number of datasets. Each set has its own properties and is shown with a separate line on the graph. Using properties you can give each dataset its own color, line style, point style or any other property that can be set for the graph as a whole. Datasets start at 0, so the first set that is created when you run addPoint with only 1 argument is the zeroth. More information about how properties effect different datasets can be found in the property section. You should always go in numerical order when using datasets. So you would add a point to the 2nd dataset like this: $graph->addPoint(1,2,1); . If you want to use the dataset property but do not want to specify what the independent variable should be use -5 for the independent. delPoint will search in all datasets for the ID. If the sort property is true the data will be sorted lowest to highest, while perserving the i-d relanshionship. It is set to true by default.

If you don't include the independent var like $graph->addPoint(5); it will just assume the next number for the independent, so if you ran the last example it assumed 0,1,2,3... for the independent var. In most cases you will have a dataset with predefined independents that you use the full syntax for, like $graph->addPoint(4,1) you can use decimal or integer values for both of the properties.

To define many points at once you can use the addBulkPoints method, it accepts a list of points like (4,2,4,5,6), an array of points, an array of points and datasets like array(array(i,d,l),array(i,d,l)...), a string of i:d pairs like ("3:3,3:2,..."), a string of l|i:d pairs (l being the dataset) like ("0|1:2,0|2:3,1|2:2") or a string of l|i pairs like ("0|1,0|3,1|3") and returns an array of the id's of the points it made.

After defining the points you have to run the graph method to actually create the graph. This is the step that takes processor time so should be done as few times as possible. Depending on the number of points and the processor speed available this usually takes from 20-50ms which is a very short amount of time. To determine the actual speed set the benchmark property to true, you'll learn about properties later in this readme. Run the graph method to graph it:

$graph->graph();

Finally, you must decide how to display the graph. In the last example you ran the showGraph method with no arguments, which inserted the image directly into the page along with the header to tell the page to process it as an image (the header can be disabled using the "noheader" property). That is fine for when you only want the image alone but if you want to insert it in a page you must tell the function the filename you want to store the image as. The showGraph function has 4 modes,

Some AJAX applications cannot store variables between server requests. Resetting all the data would take too long, insted you can store the entire graph in a file. Their are 3 specialized functions for this. storeGraph stores the graph and image to a file, it is run by providing the location for the files. $graph->storeGraph("./cache/graph.data","./cache/image.data"); if the keepcache property is set to false the cache will be automatically deleted when the object is destroyed. To retrive a stored graph use the retriveGraph and retriveImage functions. Here is a full example:

$graph = new graph();
 
 
//Set some properties and datapoints
 
 
$graph->storeGraph("datafile","imagefile");
 
 
//Later when you need to retrive it:
 
 
$graph = new graph();
 
$graph $graph->retriveGraph("datafile"); //You must set it equal to graph.
 
$graph->retriveImage("imagefile");
 
$graph->showGraph(); //Just like normal
 


Methods relating to datapoints and graphs:

NameDescriptionAcceptsReturnsExample
addPointAdds a datapoint(independent)
(independent,dependent)
(array(independent,dependent))
ID that can be used with delPoint $graph->addPoint(2,4);
delPointRemoves a datapoint(id)
(0,index)
true on success, false on failure $graph->delPoint($id);
clearPointsRemoves all datapoints()void $graph->clearPoints();
addBulkPointsAdds multiple datapoints(i1,i2,...)
("i1,i2,...")
("i1:d1,i2:d2,...")
(array(i1,d1),array(i2,d2),...)
(array(i1,i2,...)
(array(array(i1,d1),array(i2,d2),...))
Array of IDs that can be used with delPoint $graph->addBulkPoints(3,1,4,5,2);
delBulkPointsRemoves multiple datapoints(id1,id2,...)
("id1,id2,...")
(array(id1,id2,...))
Result of addBulkPoints
Array of booleans, true on success, false on failure $graph->delBulkPoints($ids);
graph(constructor)Constructor()
(Width,Height)
(Width,Height,XScalePoints,YScalePoints)
graph object $graph = new graph(100,200)
graphGenerates Graph()void $graph->graph();
showGraphMakes graph image()
("random")
(false)
("imagesrc")
image location $graph->showGraph("./images/image.png");


3. Properties:

This class uses the function setProp and setBulkProp to set the value of properties and getProp to retrive those values. Properties are optional variables that allow you to set things like colors and styles. All properties are optional and none are required to create a graph. One method to set a property is setProp:

$graph->setProp(name,value,[dataset]);

So you would use $graph->setProp("pointwidth",5) to set the width of points to 5. The setBulkProp method allows you to set many properties at once. The setBulkProps method accepts a string as its only argument, the string should be formatted "name:value,name:value,name:value". To set the value of a color using setBulkProp separate each part with a hyphen like, $graph->setBulkProp("color:red-green-blue-alpha,2|pointstyle:3,backcolor:24-122-255,1|color:blue"); . You can also use the same color names you can use in the setColor method. All the properties are listed in the function and property refrence.
To get the value of a property use the getProp method. getProp accepts the name of the property you want as a string and an optional default value. For example: $graph->getProp("endstyle",2); would return the endstyle or 2 if the endstyle property could not be found. You can also set and retrive your own user defined properties. Case does not matter. If you wish to use the same properties across multiple graphs you can use the getPropArr and storePropArr which return and store the entire property array.

Properties and datasets


When you run the setProp or setBulkProp methods without setting the dataset your properties are saved as belonging to the -1 set. The -1 set refers to global properties. When the class is looking for a property like backcolor it automatically uses the -1 set, when it looks for a property of a specific dataset it first looks in that set's properties and if it is not found their, looks in the global -1 set. To set a property of a specific set use the dataset property of the setProp method (the global set is -1, the standard set you have been using for graphing in past steps is 0, each additional set is 1,2,...). In the setBulkProp method you denote the set with a vertical slash. Heres an example of the setProp and setBulkProp methods: setProp("pointheight",10,2); or setBulkProp("2|pointheight:10"); . Always go in numerical order when using datasets.

When using the getProp method, you can specify what dataset to retrive the data from. If your data has not been defined in that set the value from the global set will be returned.



Methods relating to properties:


NameDescriptionAcceptsReturnsExample
setPropDefines a property("name","value")
("name","value",dataset)
void $graph->setProp("PointImgSrc","http://site.name/image.type");
setBulkPropDefines many properties("name:value,name:value,...")
("set|name:value,...")
("name:value","name:value",...)
(array(name,value),array(name,value),...)
(array(name,value,set),...)
void $graph->setBulkProp("pOiNtimageSRC:site.scs,ENDstyle:3,color:4-34-122-32");
getPropRetrives property("name")
("name",value to return if not defined)
("name",value to return if not defined,dataset)
value $graph->getProp("endstyle");
getPropArrRetrives entire property array()Property array $arr $graph->getPropArr();
setPropArrReplaces entire property array(Property array)null $graph->setPropArr($arr);


4. Style Options:


All of the styling is done using properties, so make sure you read section 3. You can specify the color of the background of the graph, the lines, the scale grid and numbers, the data points and the ending. You can change a color by changing the "backcolor","color","gridcolor","pointcolor" or "arrowcolor" property using the setProp method, providing an array for the value containing the red,green,blue and alpha values. The alpha value is from 0-100 and specifies how transparent the object is 0 being opaque, alpha is not required and will default to opaque. The other colors are 0-255. You can also use the setColor method, it allows you to pass an rgb value or the name of a color. Use -1 for the dataset to apply the color globaly (will be overridden by datasets if they have the same property) or for things like gridcolor that are global inherently. You could use "back","grid" or "" for the colors and "color" will be added. The setColor method is used like this: $graph->setColor("backcolor",-1,"red"); or $graph->setColor("gridcolor",-1,233,3,122); or $graph->setColor("color",-1,122,4,13,32); The accepted color strings are "red","green","blue","teal","orange","pink","purple","yellow","white","lightgray","darkgray" and "black".

Properties relating to color:

NameDescriptionDefault Value
colorLine ColorBlue
backcolorBackground ColorWhite
gridcolorScale Grid and Number ColorLight Gray
pointcolorDatapoint ColorNull
arrowcolorLine Ending ColorNull


Methods relating to color:

NameDescriptionAcceptsReturnsExample
setColorDefines a color property("object",dataset,"color")
("object",dataset,r,g,b)
("object",dataset,r,g,b,a)
void setColor("grid",-1,"orange");

The pointstyle defines what shape appears at each graph point. Set this property to 0 or don't change it to not show any shape. These are the valid point styles:

NameDescription
0No Point
1Filled Rectangle or Square
2Open Rectangle or Square
3Filled Triangle
4Open Triangle
7Filled Ellipse or Circle
8Open Ellipse or Circle
9Image (pointimgsrc must be set)


The pointwidth and pointheight properties define the size of the point, if only width is specified height defaults to width. By default the open shapes will fill the open area inside them, set the clearback property to true to stop this. The images in style 9 will be resized to the height and width. The pointimgsrc property defines the location of the jpeg,gif,png or bmp image to be imported. If the pointimgscale property is true the point height will be set depending on the pointwidth to keep the pictures width:height ratio. The pointcolor property defines the color of the points (ignored with image style).

Properties relating to points:

NameDescriptionDefault Value
pointstyleThe point style0
pointwidthThe width of points5
pointheightThe height of pointspointwidth
pointcolorThe color of pointsline color
pointimgsrcThe location of the point imagenull
clearbackDon't erase the open area inside the point?false


The endstyle defines if an arrow is used to end the graph. These are the valid arrow styles:

NameDescription
0No Arrow
1Open Arrow
2Filled Arrow


Properties relating to arrows:

NameDescriptionDefault Value
endstyleThe arrow style0
arrowwidthThe width of the arrow25
arrowangleThe angle of the arrow sides14
arrowcolorThe color of the arrowline color

Grid and Scale



The autoscl property determins whether auto scaling will be used. To set your own scaling properties set autoscl to false and set the xsclmin, xsclmax, ysclmin and ysclmax properties to set the scaling. The xsclpts and ysclpts properties define how many scale numbers and grid lines should be used. The showgrid, showhorizscale and showvertscale define if the background grid, the horizontal numeric scale and the vertical scale should be shown respectively. The sclline property defines how large each increment of the grid should be and the onfreq property defines how much of that should be the grid color and how much the back color (creating dotted lines). onfreq is a decimal value from 0 to 1, 1 being a solid line. The font, textsize and textangle properties define the font (arial is included), size and angle of the scale numbers. The actwidth and actheight properties define the true height and width of the graph image including the scale. If you wish to set the range of the graph, set the autosize propery to false and set the yMax,yMin,xMax and xMin variables. They are variables (set $graph->yMax,...) not properties.

Usually graphs will be shown in the order of their independent variable. 1,2,3... set the sort property to false to have the order be based on when you added the point.


Properties relating to grid and scale:

NameDescriptionDefault Value
autosclIf the program determins the scalingtrue
xsclminThe lowest X scale pointauto
xsclmaxThe greatest X scale pointauto
ysclminThe lowest Y scale pointauto
ysclmaxThe greatest Y scale pointauto
xsclptsThe number of scale points on the X axis10
ysclptsThe number of scale points on the Y axis6
showgridIf the grid should appeartrue
showhorizscaleIf the horizontal scale should appeartrue
showvertscaleIf the vertical scale should appeartrue
scllineThe length of each segment of the grid5
onfreqThe amount of each segment of the grid that is on.2
fontThe font used to show the numbersarial.ttf
textsizeThe size in pt of the text8
textangleThe angle of the text0
actheightThe height of the graph imageheight+30
actwidthThe width of the graph imagewidth+30
sortOrders the pointstrue

Scale


This class allows the horizontal markers to be numeric values defined by the independent variable of datapoints, dates defined by a start and end date and strings defined by the programmer. Numeric keys are automatically used, the number of keys shown is dependent on the xincpts property. Date keys are used by changing the scale property to 'date' and setting the startdate and enddate properties. By default the enddate property will use the current date, but start date must be givin a value. You can use a UNIX time stamp or the date in a string, using almost any format you wish. By default years will only be shown if your date range spans multiple years, but you can turn the year display on and off using the showyear property. You can also optionally set the dateformat property:
ValueMonth FormatYear Format
13 char2 digit
23 char4 digit
3full2 digit
4full4 digit

If you set the scale property with an array of strings, the strings will be used as keys.


Properties relating to scale:

NameDescriptionDefault Value
scaleWhat type of keys to use"numeric"
dateformatHow to format the dates1
xincptsThe number of keys to show10
showyearIf years should be shown in datesauto

Keys


The class can display a key that lists names for datasets and their corresponding color and value. The showkey property defines if the key is shown. keysize and keyfont determin the size and font of the text inside the key. keywidspc defines how much extra space is added between the graph and the left side of the key. Possible values for the keyinfo property
0No Information Beyond Name
1Percentage
2Actual Value
3Both

The key property defines what the key names are, for line graphs the keys are defined for each dataset:
<?
 $graph
->setProp("key","alpha",0);
 
$graph->setProp("key","beta",1);
 
$graph->setProp("key","delta",2);
 
?>
 OR
 <?
 $graph
->setBulkProps("0|key:alpha,1|key:beta,2|key:delta");
 
?>
 
For pie and bar charts you set the key property to an array of names:
 <?
 $graph
->setProp("key",array("alpha","beta","delta"));
 
?>
 

Properties relating to keys:

NameDescriptionDefault Value
showkeyShow keys?false
keysizeSize of the keys10
keyfontFont of the keys"arial"
keyinfoWhat information is shown in the key0
keywidspcSpace between graph and left side of key10

Titles and Labels


You can define a title, X axis label and Y axis label for the graph. The title, xlabel and ylabel properties define the text to be shown in that area. The titlesize and labelsize properties define the size of the text in those areas. The labelcolor property defines the color of the labels and is set like other colors, using the setColor method.


Properties relating to titles and labels:

NameDescriptionDefault Value
titleTitle Stringnone
xlabelX Axis Label Stringnone
ylabelY Axis Label Stringnone
titlesizeThe size of the title24
labelsizeThe size of the labels14
labelcolorThe colors of the labelsblack

Errors



When errors are triggered a description of the error in red appears on the graph, and if the error is serious a PHP error is triggered halting the execution of the program. If you set the production property to true, the red errors will not appear and PHP errors tiggered by the graph will only say "An error has occured, please contact a webmaster" insted of the error description.


Properties relating to errors

NameDescriptionDefault Value
productionHide errors?false


5. CSV, XML and MySQL data importing:


This class allows data importing using CSV (Comma separated Values) and XML (eXtensible Marking Languange). Many programs allow for data export through one or both of these formats.

CSV:

CSV importing is done through the importCSV method:
$graph->importCSV("file"[,"format"[,default dataset]]);

The file argument is simply the location of the CSV file to be imported. The format argument defines how the file is formatted. If you used "l,d,i" for the format argument it would look on each line for 3 values and use them as the dataset, dependent and independent respectively. If you are not using any of the arguments (other then dependent) simply don't include it. So just using "d" would import from a file with one number on each line, if you don't include i, it will increment by 1 each line, if you don't include l it will assume 0 unless you use the default dataset property. So these are all valid:
importCSV("file.loc","i") or importCSV("file.loc","d,i",2) or importCSV("file.loc","d,i,l")
Commas must be used.
So in this file:

0,0
1,1
2,2
3,3
4,4
5,5



You would use "d,i" for the format.

XML:

XML importing is done through the importXML method:
$graph->importXML("file"[,"independent"[,"dependent"[,"block"[,dataset]]]]);

The file is the file to be imported. Independent, dependent and block are the tags used for each in the file. In this file:


 
<data>
    <
point>
        <
i>1</i>
        <
d>4</d>
    </
point>
    <
point>
        <
i>3</i>
        <
d>6</d>
    </
point>
    <
point>
        <
i>2</i>
        <
d>3</d>
    </
point>
    <
point>
        <
i>4</i>
        <
d>5</d>
    </
point>
    <
point>
        <
i>3</i>
        <
d>5</d>
    </
point>
</
data>


You would use "i" for the independent, "d" for the dependent and "point" for the block. If no block is used you don't have to include it, use "". The data can be among other tags (like the data tag above) but does not have to be, it could just be a string of "<i>4</i><d>2</d><i>6</i><d>3</d>...". Dataset defines which dataset to put the data in, it defaults to 0. If you specify a string for dataset it will use that to find the dataset in the XML, so if "set" was your dataset and "point" was your point then you would use this: <point set=1> to specify a point in the second set (zero being the first).

MySQL Importing:

You can import data directly from a MySQL database. To do this you use the importMySQL method: <?$graph->importMySQL("table","field",resource or "database",["user",["password",["server",[frequency]]]])?> 1 You can specify the database, user, password and server if you wish to have the class connect to your database. If you need to connect to your database in a specialized way you may insted provide a MySQL resource for the database argument and omit the rest. The frequency argument determins if data is retrived by frequency of results or each result is treated as a point. You can use null for any arguments you do not want to include. A MySQL resource is created like this: <?
 $m 
mysql_connect("server","username","password");
 
mysql_select_db("database",$m);
 
$graph->importMySQL("table","field",$m);
 
?>
1 The class will graph the frequency of the values appearing in the database, see the example page.


6. Inline format:


The method used to make the CSV and XML graphs above is the inline format. For example the XML graph's code is:
<img src="<?=createGraph("XML:testdata.xml",200,100)?>">
To create inline graphs you must use the createGraph method. You run the createGraph method without creating a graph object (you do have to include the class) so you can't use $graph->createGraph, insted you preface it with graph::. You do not need to create the graph object:

graph::createGraph("data",width,height,"properties",random)

The data argument can be an XML file, a CSV file or raw datapoints. Each piece of data in the data argument must be separated by a ":" (colon). The first piece must be the format being used, either "RAW" for raw data, "XML" for an XML file or "CSV" for an CSV file. The next piece must be the file if its an XML or CSV or the data if its RAW.

For XML or CSV:
You provide the same arguments you would provide to the XML or CSV functions, separated by a colon insted of a comma. If you do not need to provide an argument just leave it out.

For RAW:
Enter data just as you would if you were using the addBulkPoints function, except you use a ; (semicolon) where you would use a : (colon). The width and height arguments define the width and height of the graph. The properties argument uses the same format as the setBulkProps method (don't replace the colons with semicolons). You can also use the property array returned from the getPropArr method as the properties argument. If their are multiple graphs on one page the filename of the image will automatically increment. You can specify a folder for the graphs to be placed in with the tempfolder property.

graph::createGraph("RAW:1;3,2;4,1;6,1|3;2,1|8;7,1|2;3",200,100,"0|color:blue,1|color:green,sort:true")


Random


The random property, if true, will add a random string of numbers to each image to prevent caching (local storage by the browser). Unless you set the delold property to false, the location of each random image will be stored as a list in a file called "imagehistory<filename where image was made>.data". The filename is included in the path so you can have multiple pages in the same folder each with their own list. Once the amount specified in the cachehistory property (default 4), images have accumulated the oldest image will be destroyed as each new is added.

Methods relating to inline graphing

NameDescriptionAcceptsReturnsExample
createGraphcreates an inline graph("format:data")
("format:data",width,height)
("format:data",width,height,"name:value,name:value",random)
filename of image createGraph("CSV:data.csv:e:d",400,100,"backcolor:red",true)

Properties relating to inline graphing

NameDescriptionDefault Value
tempfolderFolder prefix of images to be created (with trailing \)""
deloldIf old images should be deleted using randomtrue
cachehistoryHow many images to keep at once when using delold4


7. Bar Charts:

Most of this readme has focused on line graphs, but the class can also create bar charts. To create a bar chart, set the type property to 'bar'. The barwidth property is a float that sets the width of each bar, 1 is the full width allocated to them (no gap). The bars may ethier be solid colors or gradients, if solid colors are used the color property determines the color, if the colorlist property is filled with an array of arrays of rgb values each will be used to color one bar in order, if colorlist is set to true the graph will use the default colorlist. If the barstyle property is set to 1, gradients will be used, the gstartcolor and gendcolor determine the start and end colors of the bar and are set like all other colors. The bordercolor property sets the color of a 1px border surrounding the bars and only applies if solid fills are used. See the example page for demonstrations on how to use bar charts. You can switch between bar and line charts without data loss.

Properties relating to bar charts

NameDescriptionDefault Value
typeWhat type of graph to create"line"
barwidthSize of bar, as a decimal of max size1
barstyleStyle of bars, 0 is solid, 1 gradient0
colorlistArray of arrays of rgb values, will be sequentially applied to bars, true will use default valuesnull
gstartcolorBeginning color of gradient"white"
gendcolorEnd color of gradient"black"



8. Pie Charts:

This class can also create both 2D and 3D pie charts. Set the type property to "pie". The pieangle property defines what angle the pie is viewed at, 0 being a 2D graph and 90 the side of the pie. String and date keys cannot be use with pies. The useval property defines if the actual value or the percent of total is used as the key, false shows the percentage, true the actual value. The colorlist property functions slightly differently in the pie then it does in the bar charts. In pie charts a color list must be specified, but the default one used if none is specified has enough values for a 12 part graph. The numspace property defines how much extra space is given for the key, higher numbers will move the keys further from the center of the graph.

Properties relating to pie charts

NameDescriptionDefault Value
typeWhat type of graph to create"line"
pieangleAngle of pie35
usevalUse actual value, not percentage for keysfalse
colorlistArray of arrays of rgb values, will be sequentially applied to bars12 colors
numspaceExtra spacing between keys and center of graph, in pixels5


9. Function Graphing:

You can use the graphFunction method to graph mathmatical functions:
$graph->graphFunction(function,minX,maxX[,dataset]);
The function argument is the actual function you wish to graph, examples are 'x', 'pow(x,3)/2' or 'sqrt(tan(-x))'. As you can see you use x for the independent var, the function not eval'd and produces no security risk what so ever, your mathmatical function will be manually evaluated not using phps functions, so their is no security risk what so ever. The minX and maxX arguments define where the X axis starts and stops, dataset determins where the points from the function will be placed. Points will be added like any other point addition method and the function will return an array that could be passed to delBulkPoints to delete the graph. You can use the xsclpts, ysclpts, xincpts and ysclpts properies to customize the alignment of your graph. The funcinterval property defines the amount of X increment per data point, a value of .25 would create a datapoint at each .25 increment of X. You can even define your own variables and functions, for example: $graph->evaluate('f(y,e)=y^2+e') or $graph->evaluate('s=34').

Methods relating to function graphing

NameDescriptionAcceptsReturnsExample
graphFunctionGraphs a mathmatical function('function',minX,maxX)
('function',minX,maxX,dataset)
Array for use with delBulkPointsgraphFunction("-(arctan(x)*2)/(12x)",0,10);
evaluateEvaluate a mathmatical expression('expression')Resultevaluate('f(d)=(d-2)^2')

Properties relating to function graphing

NameDescriptionDefault Value
funcintervalGraph increment per data point.0625

10. Output Options:



As you learned in section 1, the showGraph method is used to display or return the graph image. The method has 4 modes, determined by what argument is passed to it:

ArgumentDescriptionBest Use
true or nothingDisplays the graph onto the page, with the png header (if noheader is not false)Sending the image to the browser directly, without an html page
falseStores the image in a file called graphImage.png, prefixed with the imagepre property, if setNormal no-frills output
"random"Stores the image in a file called graphImage<random number>.png, prefixed with the imagepre property, if setAJAX applications or where caching is a problem
any other stringStores the image to the string passed to itSpecialized output or multiple graphs on one page (without using the inline method where this is handled automatically)

The method will return the filename or true if the graph was sent to the page directly.

Properties relating to output

NameDescriptionDefault Value
noheaderDetermins if the image/png header is sent when displaying the graph directly to the pagefalse
imageprePrefix to use in default and generated image names (must include trailing /)""

Div Output
The class can output a basic form of the graph as html layers. To use this the graph object must be constructed in the head of the html document with "div" as the 5th argument in the graph constructor. This will display the graph directly to the page, set the 6th argument of the graph constructor to the id of the HTML div layer you want the graph to appear in. The document must be formatted like this:
<html><head>
<?php
include("graph.oo.php");
$graph = new graph(400,200,6,10,"div","graph");
?>
</head><body>
<div id="graph"></div>
<?php
//Points
$graph->graph();
$graph->showGraph();
?>
</body></html>

11. Method and property refrence:



Methods relating to datapoints and graphs:

NameDescriptionAcceptsReturnsExample
addPointAdds a datapoint(independent)
(independent,dependent)
(array(independent,dependent))
ID that can be used with delPoint $graph->addPoint(2,4);
delPointRemoves a datapoint(id)
(0,index)
true on success, false on failure $graph->delPoint($id);
clearPointsRemoves all datapoints()void $graph->clearPoints();
addBulkPointsAdds multiple datapoints(i1,i2,...)
("i1,i2,...")
("i1:d1,i2:d2,...")
(array(i1,d1),array(i2,d2),...)
(array(i1,i2,...)
(array(array(i1,d1),array(i2,d2),...))
Array of IDs that can be used with delPoint $graph->addBulkPoints(3,1,4,5,2);
delBulkPointsRemoves multiple datapoints(id1,id2,...)
("id1,id2,...")
(array(id1,id2,...))
Result of addBulkPoints
Array of booleans, true on success, false on failure $graph->delBulkPoints($ids);
graph(constructor)Constructor()
(Width,Height)
(Width,Height,XScalePoints,YScalePoints)
graph object $graph = new graph(100,200)
graphGenerates Graph()void $graph->graph();
showGraphMakes graph image()
("random")
(false)
("imagesrc")
image location $graph->showGraph("./images/image.png");
storeGraphStores entire graph object in a file()
("cacheLocation")
("cacheLocation","imageCacheLocation")
graphFileName
array(graphFileName,imageFileName)
$graph->storeGraph("graph.data");
retriveGraphRetrives graph object set by storeGraph()
("cacheLocation")
complete graph object $graph $graph->retriveGraph("graphCache.data");
retriveImageRetrives graph image set by storeGraph("imageCacheLocation")void $graph->retriveImage("graphImageCache.data");

Methods relating to properties:


NameDescriptionAcceptsReturnsExample
setPropDefines a property("name","value")
("name","value",dataset)
void $graph->setProp("PointImgSrc","http://site.name/image.type");
setBulkPropDefines many properties("name:value,name:value,...")
("set|name:value,...")
("name:value","name:value",...)
(array(name,value),array(name,value),...)
(array(name,value,set),...)
void $graph->setBulkProp("pOiNtimageSRC:site.scs,ENDstyle:3,color:4-34-122-32");
getPropRetrives property("name")
("name",value to return if not defined)
("name",value to return if not defined,dataset)
value $graph->getProp("endstyle");
getPropArrRetrives entire property array()Property array $arr $graph->getPropArr();
setPropArrReplaces entire property array(Property array)null $graph->setPropArr($arr);

Methods relating to inline graphing

NameDescriptionAcceptsReturnsExample
createGraphcreates an inline graph("format:data")
("format:data",width,height)
("format:data",width,height,"name:value,name:value",random)
filename of image createGraph("CSV:data.csv:e:d",400,100,"backcolor:red",true)

Methods relating to function graphing

NameDescriptionAcceptsReturnsExample
graphFunctionGraphs a mathmatical function('function',minX,maxX)
('function',minX,maxX,dataset)
Array for use with delBulkPoints graphFunction("-(arctan($x)*2)/(12*$x)",0,10);

Methods relating to color:

NameDescriptionAcceptsReturnsExample
setColorDefines a color property("object",dataset,"color")
("object",dataset,r,g,b)
("object",dataset,r,g,b,a)
void setColor("grid",-1,"orange");

Internal and development functions:

NameDescription
strimType conditional trim
xScale and yScaleGet the proper scaling for a specific data point
idSearchFind array index for a specific id
demoDataFill dataset with random data
errorTrigger error
cacheImgCache point image after resizing
multiMax and multiMinMax and Min in 2 dimensional arrays
internalGraphActual graphing, called by graph
roundRectRectangle with rounded corners, dev
loadimgLoads images
aarectAnti-Aliased rectangle, dev
imageSmoothAlphaLineSmoother lines
drawArrowheadsDraws arrowheads
flipMultiFlip keys of multidimentional array



Properties relating to color:

NameDescriptionDefault Value
colorLine ColorBlue
backcolorBackground ColorWhite
gridcolorScale Grid and Number ColorLight Gray
pointcolorDatapoint ColorNull
arrowcolorLine Ending ColorNull
bordercolorBar Border ColorBlack
colorlistList of color arrays used by bar and pie chartsArray

Properties relating to points:

NameDescriptionDefault Value
pointstyleThe point style0
pointwidthThe width of points5
pointheightThe height of pointspointwidth
pointcolorThe color of pointsline color
pointimgsrcThe location of the point imagenull
clearbackDon't erase the open area inside the point?false

Point Styles:

NameDescription
0No Point
1Filled Rectangle or Square
2Open Rectangle or Square
3Filled Triangle
4Open Triangle
7Filled Ellipse or Circle
8Open Ellipse or Circle
9Image (pointimgsrc must be set)

Arrow Styles:

NameDescription
0No Arrow
1Open Arrow
2Filled Arrow

Properties relating to arrows:

NameDescriptionDefault Value
endstyleThe arrow style0
arrowwidthThe width of the arrow25
arrowangleThe angle of the arrow sides14
arrowcolorThe color of the arrowline color

Properties relating to bar charts

NameDescriptionDefault Value
typeWhat type of graph to create"line"
barwidthSize of bar, as a decimal of max size1
barstyleStyle of bars, 0 is solid, 1 gradient0
colorlistArray of arrays of rgb values, will be sequentially applied to barsnull
gstartcolorBeginning color of gradient"white"
gendcolorEnd color of gradient"black"


Properties relating to pie charts

NameDescriptionDefault Value
typeWhat type of graph to create"line"
pieangleAngle of pie35
usevalUse actual value, not percentage for keysfalse
colorlistArray of arrays of rgb values, will be sequentially applied to bars12 colors
numspaceExtra spacing between keys and center of graph, in pixels5

Properties relating to function graphing

NameDescriptionDefault Value
funcintervalGraph increment per data point.0625

Properties relating to grid and scale:

NameDescriptionDefault Value
autosclIf the program determins the scalingtrue
xsclminThe lowest X scale pointauto
xsclmaxThe greatest X scale pointauto
ysclminThe lowest Y scale pointauto
ysclmaxThe greatest Y scale pointauto
xsclptsThe number of scale points on the X axis10
ysclptsThe number of scale points on the Y axis6
showgridIf the grid should appeartrue
showhorizscaleIf the horizontal scale should appeartrue
showvertscaleIf the vertical scale should appeartrue
scllineThe length of each segment of the grid5
onfreqThe amount of each segment of the grid that is on.2
fontThe font used to show the numbersarial.ttf
textsizeThe size in pt of the text8
textangleThe angle of the text0
actheightThe height of the graph imageheight+30
actwidthThe width of the graph imagewidth+30
sortOrders the pointstrue

Properties relating to keys:

NameDescriptionDefault Value
showkeyShow keys?false
keysizeSize of the keys10
keyfontFont of the keys"arial"
keyinfoWhat information is shown in the key0
keywidspcSpace between graph and left side of key10

Possible values for the keyinfo property

0No Information Beyond Name
1Percentage
2Actual Value
3Both

Properties relating to inline graphing

NameDescriptionDefault Value
tempfolderFolder prefix of images to be created (with trailing \)""
deloldIf old images should be deleted using randomtrue
cachehistoryHow many images to keep at once when using delold4

Properties relating to titles and labels:

NameDescriptionDefault Value
titleTitle Stringnone
xlabelX Axis Label Stringnone
ylabelY Axis Label Stringnone
titlesizeThe size of the title24
labelsizeThe size of the labels14
labelcolorThe colors of the labelsblack

Properties relating to keys:

NameDescriptionDefault Value
scaleWhat type of keys to use"numeric"
dateformatHow to format the dates1
xincptsThe number of keys to show10
showyearIf years should be shown in datesauto

dateformat Values

ValueMonth FormatYear Format
13 char2 digit
23 char4 digit
3full2 digit
4fill4 digit

Properties relating to errors

NameDescriptionDefault Value
productionHide errors?false
benchmarkDisplay how long it took to generate graph?false

Properties relating to output

NameDescriptionDefault Value
noheaderDetermins if the image header is sent when displaying the graph directly to the pagefalse
imageprePrefix to use in default and generated image names (must include trailing /)""

12. development Information:

Please report any bugs and send any suggestions to zackbloom@gmail.com. I really love to hear both.

Really want a feature? Guilt me into making it by donating:

Please send any bug reports with a print_r of the graph object if possible.
Works with PHP5 with GD and TTF support.
Developed by Zack Bloom

Licence
You can do what ever you want with the code, copy all or part, impress girlfriends with your l33t programming skillz, say you wrote it, whatever. The only condition is, and I'm serious about this, if you use it in any commercial applications you must give me a free copy. But I must say it is much more gratifying to write the code yourself (unless it actually takes effort like the AA lines or arrow heads that I stole functions for, then steal away). You don't even have to give me credit, just send me a link to any thing cool you make, zackbloom@gmail.com.

I need to feel loved, send me a link to anything you make: zackbloom@gmail.com

ToDo List: