您的位置:首页 > 编程语言 > PHP开发

一个PHP图表绘制类 - Chart

2007-06-21 10:25 357 查看
Chart是一个使用PHP写的图表类,调用GD库来进行画图操作,最后维护时间是2004年,通用性不一定很强,但是绘制图表功能还不错,可以绘制自己需要一些简单的图表。

下载地址:http://quimby.gnus.org/circus/chart/chart-0.8.tar.gz
手册:http://quimby.gnus.org/circus/chart/chart-manual.php



ChartManual




ChartisaPHP4libraryforgeneratingcharts--twodimensionalrepresentationsofdatasets.ThisisthemanualforChart0.8.

ChartiscoveredbytheGNUGPLandiswrittenbyLarsMagneIngebrigtsen.DevelopmentofthislibrarywaspaidforbyNetFondsASA.

Download

Atarredandgzippedpackageofthelatestversionofthelibrary.

Asuper-quickexample

Beforegettingdowntothebusinessathand,let'sjusthavealookataquickexampleofwhatChartismeanttodo,andhowitdoesit.

ThesimplestChartprogramimaginableistheonethatgeneratedtheimagetotheright.Thesourcecodeisthefollowing:



$chart=newchart(300,200);
$chart->plot($data);
$chart->stroke();

Thisdemonstratesthefollowing:

Chartisaclass

Youcreateanewchart,andthendostuffwithituntilyoustrokeit

Scalingisdoneautomaticallybydefault

Gridsandticksarecomputedinamore-or-lesssensiblewaybydefault

Afterthatmini-introduction,themanualwillnowcontinueasscheduled:

Rationale

IworkforanInternetstockbroker,andweneededtoallowuserstogeneratechartsfromourwebpages.OnesmartwaytodothatwouldbetocreateJavaappletsandpushthecomputationouttotheclients,buttherearesomeproblemswiththat(stability,usabilityandthedifficultywhenprintingthemout--thelatterisveryimportantinfinancialcircles).Sowewantedtogeneratethegraphsonthewebservers,andjustservethemoutasimages.

TherestofourwebsiteisPHP-based,soitwasnaturaltowanttousePHPforgeneratingthegraphs.Onelessthingthatcangowrongisonelessthingthatcangowrong.

Asanoldengnuplotuser,myfirstimpulsewastocreatesomethingthatresembledthat,butIquicklyrealizedthatmyhubriswasn'tthatoverwhelming--yet.Gnuplotisanexcellent,flexible,complexprogram,butitsfunctionalityisoverkillforwhatIneed.Idonotneedtoplotthree-dimensionaldatasetsusingesotericfunctions.Ihaveactualtwo-dimensional(ordefactotwo-dimensional)datasetsthatIwishtohavepresentedgraphically.Chartattemptstofillthat(muchsimpler)need.

Ihavetriedtoemphasizeeaseofuse--Chartusuallycomputesalltheboringstuffitself.However,mosteverythingthatChartdoescanbeoverriddenorcustomizedifyouwantadifferentlook.

Abouttheexamples

Alltheexamplechartsare,ofcourse,generatedbyChart.Thedatasetsforthechartscomefromastaticdatafile,butnormallyonewouldgetthedatasetsfromadatabaseorsomethingsimilar.

Theactualsourcecodeforallthechartscanbereadbyclickingonthecharts.

PHP4

ChartneedsPHP4.PHP3hasamuchtooweakobjectmodeltoallowworkingwithanon-trivialsetofobjectsinasensiblemanner.PHP4canbegottenfromthePHPwebsite.Theonlynon-standardlibraryChartreliesonisRGB,whichmakesitmucheasiertodealwithcolors.RGBisincludedintheChartpackage.

Functionreference

TherearetwoclassesintheChartlibrary--chartandplot.Eachchartcancontainanynumberofplots.



Here'sachartwithtwoplots:

ChartFunctions

chart

chart(int$width,int$height,string$cache=false)

Createachartobjectofthespecifiedsize.Iftheoptional$cacheparameterissupplied,thecacheismaintained.

set_border

set_border(color$color="black",int$width=1)

Drawaborderaroundthechartusingthespecifiedcolorandwidth.Ifyouspecifyfalseasthecolor,noborderwillbedrawn.



set_background_color

set_background_color(color$color="white",
color$surround="white")

Setsthebackgroundcolorofthechart.The"surrounding"coloristhecoloroftheareabetweenthechartitselfandtheouterborder.

set_x_ticks

set_x_ticks(array$ticks,$format="date")

SpecifywheretheXaxisticktextsaresupposedtocomefrom.Theywillbeformattedaccordingtotheinputformatspecified.Thefollowinginputformatsaresupported:



"date":ThedateinISO8601format.

"time":ThetimeinISO8601format.

"cdate":ThedateinUnixformat.

"ctime":ThetimeinUnixformat.

"text":Simpletext.

ISO8601formatlookslikeYYYYMMDDThhmmss.UnixtimeformatisthenumberofsecondssinceJanuary1st1970.

set_title

set_title(string$title,color$color="black",string$where="center")

Setthetitleofthechart.Thepositioningparametercanbe"center","left"or"right",oranarraywithtwoelements--theXandYpositionoftheleft-andtopmostpixelofthetitle.

set_axes

set_axes(string$which="xy",color$color="black")

Specifywhichaxestodraw,andthecoloroftheaxes.Youcanhave"y","x"or"xy"axesdrawn.

splot

splot(plot&$plot)

Addsplot$plottothechart.Here'sacodesnippettoillustrate:

$chart=newchart(100,200);
$plot=newplot($data);
$chart->splot(&$plot);

You'dnormallynotusethisfunction,butusetheplot()functioninstead.

plot

plot(array$c1,array$c2=false,color$color="black",
string$style="lines",color$gradient_color="black",
int$parameter=0)

Registereitheraone-dimensionaldatasetor(if$c2isanarray)atwo-dimensionaldatasettobeplotted.Botharraysmustbeone-dimensional.Thisfunctionreturnsaplotobject.Seeset_style()foralistingofpossiblestyles.

stroke

stroke(function$callback=false)

Thisisthefunctionthatdoesallthework.Noneoftheotherfunctionsactuallycomputeanything--theyjustregisterthings.Thisfunctionlooksateverythingthathasbeenregistered,computeseverything,outputstheproperHTTPheadersandoutputstheresultingimage(inGIFformat).

Iftheplotneedsspecialhandling,youcansupplyacall-backfunction.Thenstrokewillcomputeeverything,dothegridandtheaxes(etc.),andthencallthecall-backfunctionwiththefollowingsignature:

$callback($image,$xmin,$xmax,$ymin,$ymax,
$xoffset,$yoffset,$width,$height);

Thenitisuptothecall-backfunctiontodrawthedataset.



set_frame

set_frame($frame=true)

Drawaframearoundtheplottedarea,usingthesamecolorastheborder.

set_expired

set_expired(bool$expired)

Iftheimagesyougeneratearetrulydynamic,thenyouprobablywanttoprohibitthewebbrowserandanyproxies/cachesfromstoringtheimages.Callingthisfunctionwithanon-falsevaluewillmakeChartoutputheaderstodiscouragecachingontheclientside.Notethatthiswillprobablyresultinmuchhighertraffic.




set_extrema

set_extrema(int$y_min=false,int$y_max=false,
int$x_min=false,int$x_max=false)

Bydefault,scalingisdoneautomatically.Chartcomputesalltheextremaandadds1%fudgespace.Ifyouwanttomanuallysettheextrema(forinstance,ifyou'regeneratingseveralchartsandwanttokeepthesamescalingonallthecharts),youcanusethisfunctiontospecifytheextrema.

Forinstance,theimagetotherightusesthesamedataastheoneabove,buthastheYextremasetmuchwiderthanthedefaultalgorithmwouldhavedone.

set_grid_color

set_grid_color(Color$color)

Setthecolorofthegrid.

set_margins

set_margins(int$left=30,int$right=10,
int$top=20,int$bottom=23)

Setthewidthofthemargins.

set_tick_distance

set_tick_distance(int$distance)

Setthedistance(inpixels)betweentheticksontheaxes.



set_labels

set_labels(string$x=false,string$y=false)

SettheXandYlabelsofthechart.

set_output_size

set_output_size(int$width,int$height)

Settheoutputsizetosomethingelsethanthesizeyoucreatethechartat.Thiscanbeusefulifyouwanttocreateaverysmallchart,andwanttoplotitatabiggersize,andthenresizeitdowntoasmallsize,sothatyoucangetantialiasedresampling.ThisonlyworksifyouhavePHPcompiledwiththe2.0versionofthegdlibrary(andsetthe$gd2variabletotrue).Ifnot,theresizingwillbevery,veryugly.

set_grid_color

set_grid_color(color$grid_color,
bool$grid_under_plot=true)

Setthecolorofthegrid.Optionallysaywhetherthegridshouldbeunderthedataplot(whichisthedefault),oroverit(whichisusefulifplottingusingthe"fill"or"gradient"plotstyles.




set_font

set_font($font,$type,$size=false)

Setthefontusedforthetitleandlabels.Threefonttypescanbeused:



"internal":TheinternalPHPfonts.The$fontparametershouldbeanintegerbetween0and8.

"type1":Atype1PSfont.The$fontparametershouldbethepathtoafilecontainingthePFBfontfileforthetype1font.Tousethis,yourPHPhastobecompiledwithsupportfortype1fonts.(I.e.,thet1liblibraryhastobecompiledin.)

"ttf":ATrueTypePSfont.The$fontparametershouldbethepathtoafilecontainingtheTTFfontfileforthettffont.Tousethis,yourPHPhastobecompiledwithsupportforTTFfonts.(I.e.,thefreetypelibraryhastobecompiledin.)

MostUnixoidpeoplewillwanttouseType1fonts,astheseareincludedinallTeXdistributions.Justsaysomethinglike

$chart->set_font("/usr/share/texmf/fonts/type1/adobe/utopia/putb8a.pfb",
		"type1");

togetthechartabove.




Ifyouspecifytheoptional$sizeparameter,thefontwillbescaledusingthatpointsize.Theparameterhasnoeffectforinternalfonts.

UsingType1orTTFfontswillmakeChartalotslower.Cachingisanabsolutemustisyoudon'tusetheinternalfonts.




add_legend

add_legend($string,$color)

Addalegendtothechart.Thefollowingvariablescanbesettotunethelegend:



$legend_background_color:Thebackgroundcolorofthelegend.Ifsettofalse,thebackgroundofthelegendwillbetransparent.

$legend_border_color:Thebordercolorofthelegend.Ifsettofalse,noborderwillbedrawn.

$legend_margin:Thesizeofthemargin,inpixels,betweenthelegendtextandthelegendborder.

PlotFunctions

set_color

set_color(color$color)

Setthecoloroftheplot.
set_style($style)

Setthestyleoftheplot.Validvaluesare"lines","points","impulse","circle","cross","fill","square","triangle","box"and"gradient".



"lines":Drawangledlinesbetweendatapoints.

"square":Drawsquarelinesbetweendatapoints.

"points":Plotthedatapointswithdots.

"impulse":Drawalineupwardsfromthebottomtothedatapoint.

"circle":Plotthedatapointsusingcircles.Takesanoptionalcirclesizeparameter.

"cross":Plotthedatapointsusingcrosses.Takesanoptionalcrosssizeparameter.

"fill":Taketwodatasetsandfilltheareabetweenthem.Thedatapointsthemselveswillbedrawnusing"square".

"fillgradient":Thesameasfill,butusesagradient,asexplainedbelow.

"triangle":Plotthedatapointsusingtriangles.Takesanoptional"shadowcolor"paramater.

"box":Plotthedatapointsusingboxes.Takesanoptionalgradientcolorparameter--threecolorswillbeused,intotal.

"gradient":Filltheareaunder/overthedataplotwithagradientcolor.Asecondarycolorisgiven,andaparametercanalsobeusedtocontrolthegradientevenfurther.Theparameterisabitmask,andthefollowingbitsaredefined:



1(style):Ifset,drawusingadynamicstyle.Ifnotset,eachYvaluewillhavethesamecolor.

2(over/under):Ifset,drawoverthedataplot.Ifnotset,drawunderthedataplot.

4(from/to):Reversethedirectionofthegradient.

8(horizontal):Graduatehorizontallyinsteadofvertically.




Belowisthesamedatasetplottedusingdifferentstyles.






















Belowisthesamedatasetplottedusingthe"gradient"style,butwithdifferentparameters.



























And,ofcourse,youcangocompletelywildandplotseveraldifferentgradientsinthesamechart:







Theusefulnessofthesechartsmayberatherquestionable.Placingthegridovertheplothelpssome:







Andfinally,fillandfillgradientplots:







Plottingtheupperandlowerboundsseparatelyoftenmakesthefillingplotslooknicer:





Usinggradientsmeansslowingdownchartgenerationsomewhat.Dynamicgradientsarenoslowerthatnon-dynamicgradients,butusingthemmeansthatthechartswillbequiteabitlarger,sincetheywon'tcompressaswellasnon-dynamicgradients.Ifyouhaveaheavyload,oryouhaveaslowwebserver,youshouldtrytocachethegradientchartsasaggressivelyaspossible.

Caching

PHPisnotthemostefficientlanguageintheworld,andifyouhaveabusywebsite,generatingmassesofimagesmaybogyourserverdown.Chartthereforehasacachingmechanism.

Ifyousupplyathirdparametertothechartfunction,thenChartwillfirstchecktoseeifthatfileexistsbeforedoinganything.Ifitdoes,itwilloutputthatfileandexit.Ifitdoesnotexist,Chartwillcomputethechartasusual,butbeforeoutputtingthenewly-generatedchart,itwillsaveittothecachefirst,usingthatsuppliedfilename.

PHPscriptsthatusethiswouldhavesomethinglikethefollowingatthestartofthescript:

$chart=newchart(200,100,"nice-plot");
#...Therestoftheprogram.

ThenPHPwouldonlycreatetheimageonce,andeveryotheraccesswouldbedealtwithfromthecache.

Inthiscase,thiswouldproduceatotallystaticplot,andyoumightaswelljustgeneratetheGIFandusethatinsteadofthePHPscript.Onereasontostilldoitthiswayisthatit'softenjustsimpler.Forinstance,alltheexampleplotsyou'reseeingonthispagemostprobablycamefromthecache.

Mostrealdynamicplotsusuallyhavesomeinputvalues,though.Arecommendedwaytodealwiththatwouldbe:

$chart=newchart(200,100,
sprintf("other-plot/stuff=%d/thing=%s/gif",
$stuff,$thing);
#...Therestoftheprogram.

Thischartdependsontwoparameters--stuffandthing.Ifthesevarywildly,manyGIFswillbegeneratedandstoredinthecache.Inthatcase,settingupacronjobtodeleteimagesthathaven'tbeenaccessedin,say,afewdays,wouldbenecessary.Somethinglikethefollowingwouldprobablydothetrick;itfirstdeletesallfilesthathaven'tbeenaccessedinthreedays,andthenitremovesallemptydirectories:

#!/bin/sh
find/var/tmp/cache-typef-atime+3-execls-l{}/;
find/var/tmp/cache-typed-empty-execls-ld{}/;

Thisshould,ofcourse,berunasthesameuserthatgeneratedthefiles,whichwouldnormallybenobody.

Itisprobablynotagoodideatogenerateaflatcache.Ifmanythousandimagesarecached,accessingfilesinsuchabigdirectorywillbeslow.Thereforeitisprobablyusuallybettertogenerateatreestructure,asshownintheexampleabove.

Ifyourplotisnotuniquelydeterminedbytheparameters,cachingbecomesproblematic,andwillgiveyoubadresults.If,forinstance,youhaveachartthatdisplaysdifferentdatadependingonthedate,youcouldgetaroundthisproblembyincludingthedateinthecachefilename.Thenthechartwouldonlybegeneratedonceperday.

Whiledevelopingnewcharts,thecacheusuallygetsintheway.Ifthat'sthecase,settheglobal$chart_debugvariabletotrue.ThiswilloverridethecacheandforceCharttore-generatetheimageseverytime.

Theglobal$chart_cache_directoryvariablesayswhattherootdirectoryofthecacheis.Itdefaultsto"/var/tmp/cache".

GIFandPNG

Asofversion0.4,ChartdefaultstooutputtingPNGimagesinsteadofGIFimages.Thisisbecausenewerversionsofthegdlibrary(whichPHPusestocreateimages)doesn'tincludeGIFcreatingfunctions,sincethepatentholderstotheGIFalgorithmdemandmoneyfortheusageofthatalgorithm.IfyouabsolutelyhavetogenerateGIFimages(andthere'sreallynoneed,sinceallmodernwebbrowsersparsePNGimagesjustfine),youneedtolinkPHPwithgdversion1.3orearlier,andsettheglobal$chart_use_pngvariabletofalse.

Gridsandticks

ChartusesheuristiscsdevelopedovertheyearstofindpleasingnumberstoputontheXandYaxes,aswellasspacingthegridlinesinasensibleway.Moreworkneedstobedone,butthefollowingseemstoworkquitewell:



OntheYaxes,numbersdivisibleby1,2and5areused.(Dividedandmultipliedby10,etc.)

IftheXaxesisaclockaxes(i.e.,time),Charttriestousewholehours,halfhours,quarterhours,etc.

FordatesontheXaxes,Charttriestouseyears,months,weeks,etc.

Bugs

Charthasn'tbeenoptimizedforspeedatall.Thereareprobablymanythingsonecandotomakeitrunfaster.Patchesarewelcome.

Possiblecomingfeatures

Puttingtextandotherimagesintothechartsmightbenice.Namingtheplotswouldbeconvenient.Andjustaboutanythingelsethatgnuplotdoeswithtwo-dimensionalplotswouldbespiffy.

OtherPHPPackages

AtthetimewhenIstartedwritingChart,therewasn'tanythinglikeitavailable.Nowthereareseveralotherpackagesthatdoessimiliarthings,usingdifferentapproaches.OneinterestingpackageisJpGraph,whichseemstobeabletogenerateverynicechartsindeed.Thatpagealsohaslinkstootherpackages.

Contributors

ChristophLametersuppliedpatchesforcdate,ctime,boxandtriangleextensions.

HoSiawPing,Ryanfixedthex_tickscode.

Bugs

Ifyouuseadifferentlocalethanenglish,stuffwillprobablynotworkwell.setlocale(LC_ALL,"english");tosettherightlocale.

Contact

Chartis©1999,2000,2001LarsMagneIngebrigtsen.

ChartisreleasedundertheGNUGeneralPublicLicense.ThismeansthatChartisfree.ThiswebpageisthedocumentationtoChartandiscoveredbythesamelicense.

Patches,newfeatures,bugreportsandotherstuffcanbesenttoLarsMagneIngebrigtsen.




2001-11-0821:44:14

set_style

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: