一个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
ChartisaPHP4libraryforgeneratingcharts--twodimensionalrepresentationsofdatasets.ThisisthemanualforChart0.8.
ChartiscoveredbytheGNUGPLandiswrittenbyLarsMagneIngebrigtsen.DevelopmentofthislibrarywaspaidforbyNetFondsASA.
Atarredandgzippedpackageofthelatestversionofthelibrary.
ThesimplestChartprogramimaginableistheonethatgeneratedtheimagetotheright.Thesourcecodeisthefollowing:
Thisdemonstratesthefollowing:
Chartisaclass
Youcreateanewchart,andthendostuffwithituntilyoustrokeit
Scalingisdoneautomaticallybydefault
Gridsandticksarecomputedinamore-or-lesssensiblewaybydefault
Afterthatmini-introduction,themanualwillnowcontinueasscheduled:
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.
astaticdatafile,butnormallyonewouldgetthedatasetsfromadatabaseorsomethingsimilar.
Theactualsourcecodeforallthechartscanbereadbyclickingonthecharts.
thePHPwebsite.Theonlynon-standardlibraryChartreliesonisRGB,whichmakesitmucheasiertodealwithcolors.RGBisincludedintheChartpackage.
Here'sachartwithtwoplots:
Createachartobjectofthespecifiedsize.Iftheoptional$cacheparameterissupplied,thecacheismaintained.
Drawaborderaroundthechartusingthespecifiedcolorandwidth.Ifyouspecifyfalseasthecolor,noborderwillbedrawn.
Setsthebackgroundcolorofthechart.The"surrounding"coloristhecoloroftheareabetweenthechartitselfandtheouterborder.
SpecifywheretheXaxisticktextsaresupposedtocomefrom.Theywillbeformattedaccordingtotheinputformatspecified.Thefollowinginputformatsaresupported:
"date":ThedateinISO8601format.
"time":ThetimeinISO8601format.
"cdate":ThedateinUnixformat.
"ctime":ThetimeinUnixformat.
"text":Simpletext.
ISO8601formatlookslikeYYYYMMDDThhmmss.UnixtimeformatisthenumberofsecondssinceJanuary1st1970.
Setthetitleofthechart.Thepositioningparametercanbe"center","left"or"right",oranarraywithtwoelements--theXandYpositionoftheleft-andtopmostpixelofthetitle.
Specifywhichaxestodraw,andthecoloroftheaxes.Youcanhave"y","x"or"xy"axesdrawn.
Addsplot$plottothechart.Here'sacodesnippettoillustrate:
You'dnormallynotusethisfunction,butusetheplot()functioninstead.
Registereitheraone-dimensionaldatasetor(if$c2isanarray)atwo-dimensionaldatasettobeplotted.Botharraysmustbeone-dimensional.Thisfunctionreturnsaplotobject.Seeset_style()foralistingofpossiblestyles.
Thisisthefunctionthatdoesallthework.Noneoftheotherfunctionsactuallycomputeanything--theyjustregisterthings.Thisfunctionlooksateverythingthathasbeenregistered,computeseverything,outputstheproperHTTPheadersandoutputstheresultingimage(inGIFformat).
Iftheplotneedsspecialhandling,youcansupplyacall-backfunction.Thenstrokewillcomputeeverything,dothegridandtheaxes(etc.),andthencallthecall-backfunctionwiththefollowingsignature:
Thenitisuptothecall-backfunctiontodrawthedataset.
Drawaframearoundtheplottedarea,usingthesamecolorastheborder.
Iftheimagesyougeneratearetrulydynamic,thenyouprobablywanttoprohibitthewebbrowserandanyproxies/cachesfromstoringtheimages.Callingthisfunctionwithanon-falsevaluewillmakeChartoutputheaderstodiscouragecachingontheclientside.Notethatthiswillprobablyresultinmuchhighertraffic.
Bydefault,scalingisdoneautomatically.Chartcomputesalltheextremaandadds1%fudgespace.Ifyouwanttomanuallysettheextrema(forinstance,ifyou'regeneratingseveralchartsandwanttokeepthesamescalingonallthecharts),youcanusethisfunctiontospecifytheextrema.
Forinstance,theimagetotherightusesthesamedataastheoneabove,buthastheYextremasetmuchwiderthanthedefaultalgorithmwouldhavedone.
Setthecolorofthegrid.
Setthewidthofthemargins.
Setthedistance(inpixels)betweentheticksontheaxes.
SettheXandYlabelsofthechart.
Settheoutputsizetosomethingelsethanthesizeyoucreatethechartat.Thiscanbeusefulifyouwanttocreateaverysmallchart,andwanttoplotitatabiggersize,andthenresizeitdowntoasmallsize,sothatyoucangetantialiasedresampling.ThisonlyworksifyouhavePHPcompiledwiththe2.0versionofthegdlibrary(andsetthe$gd2variabletotrue).Ifnot,theresizingwillbevery,veryugly.
Setthecolorofthegrid.Optionallysaywhetherthegridshouldbeunderthedataplot(whichisthedefault),oroverit(whichisusefulifplottingusingthe"fill"or"gradient"plotstyles.
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
togetthechartabove.
Ifyouspecifytheoptional$sizeparameter,thefontwillbescaledusingthatpointsize.Theparameterhasnoeffectforinternalfonts.
UsingType1orTTFfontswillmakeChartalotslower.Cachingisanabsolutemustisyoudon'tusetheinternalfonts.
Addalegendtothechart.Thefollowingvariablescanbesettotunethelegend:
$legend_background_color:Thebackgroundcolorofthelegend.Ifsettofalse,thebackgroundofthelegendwillbetransparent.
$legend_border_color:Thebordercolorofthelegend.Ifsettofalse,noborderwillbedrawn.
$legend_margin:Thesizeofthemargin,inpixels,betweenthelegendtextandthelegendborder.
Setthecoloroftheplot.
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.
Ifyousupplyathirdparametertothechartfunction,thenChartwillfirstchecktoseeifthatfileexistsbeforedoinganything.Ifitdoes,itwilloutputthatfileandexit.Ifitdoesnotexist,Chartwillcomputethechartasusual,butbeforeoutputtingthenewly-generatedchart,itwillsaveittothecachefirst,usingthatsuppliedfilename.
PHPscriptsthatusethiswouldhavesomethinglikethefollowingatthestartofthescript:
ThenPHPwouldonlycreatetheimageonce,andeveryotheraccesswouldbedealtwithfromthecache.
Inthiscase,thiswouldproduceatotallystaticplot,andyoumightaswelljustgeneratetheGIFandusethatinsteadofthePHPscript.Onereasontostilldoitthiswayisthatit'softenjustsimpler.Forinstance,alltheexampleplotsyou'reseeingonthispagemostprobablycamefromthecache.
Mostrealdynamicplotsusuallyhavesomeinputvalues,though.Arecommendedwaytodealwiththatwouldbe:
Thischartdependsontwoparameters--stuffandthing.Ifthesevarywildly,manyGIFswillbegeneratedandstoredinthecache.Inthatcase,settingupacronjobtodeleteimagesthathaven'tbeenaccessedin,say,afewdays,wouldbenecessary.Somethinglikethefollowingwouldprobablydothetrick;itfirstdeletesallfilesthathaven'tbeenaccessedinthreedays,andthenitremovesallemptydirectories:
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".
OntheYaxes,numbersdivisibleby1,2and5areused.(Dividedandmultipliedby10,etc.)
IftheXaxesisaclockaxes(i.e.,time),Charttriestousewholehours,halfhours,quarterhours,etc.
FordatesontheXaxes,Charttriestouseyears,months,weeks,etc.
JpGraph,whichseemstobeabletogenerateverynicechartsindeed.Thatpagealsohaslinkstootherpackages.
HoSiawPing,Ryanfixedthex_tickscode.
ChartisreleasedundertheGNUGeneralPublicLicense.ThismeansthatChartisfree.ThiswebpageisthedocumentationtoChartandiscoveredbythesamelicense.
Patches,newfeatures,bugreportsandotherstuffcanbesenttoLarsMagneIngebrigtsen.
2001-11-0821:44:14
下载地址:
手册:
ChartManual
ChartisaPHP4libraryforgeneratingcharts--twodimensionalrepresentationsofdatasets.ThisisthemanualforChart0.8.
Chartiscoveredbythe
Download
Asuper-quickexample
Beforegettingdowntothebusinessathand,let'sjusthavealookataquickexampleofwhatChartismeanttodo,andhowitdoesit.ThesimplestChartprogramimaginableistheonethatgeneratedtheimagetotheright.Thesourcecodeisthefollowing:
$chart=newchart(300,200); $chart->plot($data); $chart->stroke();
Thisdemonstratesthefollowing:
Chartisaclass
Youcreateanewchart,andthendostuffwithituntilyou
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.ThedatasetsforthechartscomefromTheactualsourcecodeforallthechartscanbereadbyclickingonthecharts.
PHP4
ChartneedsPHP4.PHP3hasamuchtooweakobjectmodeltoallowworkingwithanon-trivialsetofobjectsinasensiblemanner.PHP4canbegottenfromFunctionreference
TherearetwoclassesintheChartlibrary--chartandplot.Eachchartcancontainanynumberofplots.Here'sachartwithtwoplots:
ChartFunctions
chart
chart(int$width,int$height,string$cache=false)
Createachartobjectofthespecifiedsize.Iftheoptional$cacheparameterissupplied,the
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.Thisfunctionreturnsa
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.OneinterestingpackageisContributors
ChristophLametersuppliedpatchesforcdate,ctime,boxandtriangleextensions.HoSiawPing,Ryanfixedthex_tickscode.
Bugs
Ifyouuseadifferentlocalethanenglish,stuffwillprobablynotworkwell.setlocale(LC_ALL,"english");tosettherightlocale.Contact
Chartis©1999,2000,2001LarsMagneIngebrigtsen.Chartisreleasedunderthe
Patches,newfeatures,bugreportsandotherstuffcanbesentto
2001-11-0821:44:14
set_style
相关文章推荐
- 一个PHP图表绘制类 - Chart
- 一个PHP图表绘制类 - Chart
- 一个PHP图表绘制类 - Chart
- Android图表库HelloChart绘制多折线图
- 用 chart.js 创建漂亮图表 (HTML绘制工具库)
- chart.js绘制移动端图表
- qt +ChartDirector 绘制图表
- 【Android 应用开发】Android 图表绘制 achartengine 示例解析
- Android 图表绘制 achartengine 示例解析
- Asp.net 2.0 自定义控件开发[开发一个图表(WebChart)控件(柱状图示例)](示例代码下载)
- Asp.net 2.0 自定义控件开发[开发一个图表(WebChart)控件(柱状图示例)](示例代码下载)
- PHPExcel探索之旅---阶段三 绘制图表
- PHP笔记——chart图表JpGraph
- 在Dreamweaver下创建一个php文件并用正确使用php“绘图函数”进行绘制图形时,图形却无法显示
- 【转】使用DevExpress的WebChartControl控件绘制图表(柱状图、折线图、饼图)
- 开源PHP & Flash图表:Open Flash Chart
- Chart.js 轻量级HTML5图表绘制工具库(知识整理)
- 使用DevExpress的WebChartControl控件绘制图表(柱状图、折线图、饼图)
- Asp.net 2.0 自定义控件开发[开发一个图表(WebChart)控件(柱状图示例)](示例代码下载)
- Android 图表绘制 achartengine 示例解析