您好,欢迎访问三七文档
D3技术应用注释——使用D3添加坐标轴1、简要说明介绍了如何使用D3给图形添加坐标轴。、以下是实际内容HavingmasteredtheuseofD3scales,wenowhavethisscatterplot:Let’saddhorizontalandverticalaxes,sowecandoawaywiththehorriblerednumbersclutteringupourchart.通过在上面的散点图添加横坐标或纵坐标轴,来学习D3的坐标轴功能。强烈建议在看懂2012-09-24_D3_C08Tutorials_15_Scale.docx的基础上,来看这篇文章。IntroducingAxesMuchlikethescalefunctions,D3’saxesareactuallyfunctionswhoseparametersyoudefine.Unlikescales,whenanaxisfunctioniscalled,itdoesn’treturnavalue,butgeneratesthevisualelementsoftheaxis,includinglines,labels,andticks.NotethattheaxisfunctionsareSVG-specific,astheygenerateSVGelements.Also,axesareintendedforusewithquantitativescales(asopposedtoordinalones).就像标度变换功能一样,D3的坐标由你给定的参数来定义。不同的是,当调用坐标轴函数时,不返回值,而生成实际的坐标图像元素。包括轴线、坐标、刻度。特别注意,坐标轴函数生成的坐标轴是SVG的功能,用的是SVG元素。(line等)。D3仅是提供了一个更为简便的接口。SettingupanAxisUsed3.svg.axis()tocreateagenericaxisfunction:varxAxis=d3.svg.axis();Ataminimum,eachaxisalsoneedstobetoldonwhatscaletooperate.Herewe’llpassinthexScalefromthescatterplotcode:xAxis.scale(xScale);可以使用d3.svg.axis()功能创建轴对象,使用轴对象,至少要指定scale。这里的xScale指的是上一张Tutorials15中画散点图用的xScale。但是对于NV封装的d3来说,这点也是不必要的。D3的封装还仅是提供方便的操作SVG的接口,如点、线、圆、矩形等。Nv的封装则提供方便的操作各种图表的接口。比D3更高一层。例如,对于NV封装,可以直接定义scatter对象来画散点图,给scatter关联的数据data,会自动用于处理坐标轴。从这一点上来说,要改变NV封装的唯一方式,仅有深入NV修改其内部的内容。Wecanalsospecifywherethelabelsshouldappearrelativetotheaxisitself.Thedefaultisbottom,meaningthelabelswillappearbelowtheaxisline.(Althoughthisisthedefault,itcan’thurttospecifyitexplicitly.)xAxis.orient(bottom);通过orient来定义坐标轴显示与图标上方还是下方。Ofcourse,wecanbemoreconciseandstringallthistogetherintooneline:varxAxis=d3.svg.axis().scale(xScale).orient(bottom);Finally,toactuallygeneratetheaxisandinsertallthoselittlelinesandlabelsintoourSVG,wemustcallthexAxisfunction.I’llputthiscodeattheendofourscript,sotheaxisisgeneratedaftertheotherelementsintheSVG:svg.append(g).call(xAxis);D3’scall()functiontakesaselectionasinputandhandsthatselectionofftoanyfunction.So,inthiscase,wehavejustappendedanewggroupelementtocontainallofourabout-to-be-generatedaxiselements.(Thegisn’tstrictlynecessary,butkeepstheelementsorganizedandallowsustoapplyaclasstotheentiregroup,whichwe’lldoinamoment.)最后,如果要确实生成坐标轴并插入所有线元素和刻度到SVG中,我们必须调用xaxis函数,调用方法是.call(xAxis)。Call函数,会获取当前的selection,并把该selection作为输入一次传递给对应的函数供其使用和处理。因此,在上面的例子中,call中应该包含生成坐标轴所需要的所有信息。Thatgbecomestheselectionforthenextlinkinthechain.call()handsthatselectionofftothexAxisfunction,soouraxisisgeneratedwithinthenewg.Thatsnippetofcodeaboveisjustnice,cleanshorthandforthisexactequivalent:svg.append(g).call(d3.svg.axis().scale(xScale).orient(bottom));上面的程序中,svg.append(“g”),产生一个g容器。(g容器,是SVG的一个标签,参考SVG元素)Call获得该g,作为selection,将selection交由d3.svg.axis处理。产生的坐标轴,用xScale的domain作为起始和结束值,用xScale的range作为x轴起始和结束点在SVG的位置。See,youcouldcramthewholeaxisfunctionwithincall(),butit’susuallyeasieronourbrainstodefinefunctionsfirst,thencallthemlater.Inanycase,here’swhatthatlookslike:CleaningitUpTechnically,thatisanaxis,butit’sneitherprettynoruseful.Tocleanitup,let’sfirstassignaclassofaxistothenewgelement,sowecantargetitwithCSS:这个坐标轴既不美观也不实用,为了更适于我们的需要,实用层叠样式表对坐标轴进行处理,svg.append(g).attr(class,axis)//Assignaxisclass.call(xAxis);Then,weintroduceourfirstCSSstyles,upintheheadofourpage:.axispath,.axisline{fill:none;stroke:black;shape-rendering:crispEdges;}.axistext{font-family:sans-serif;font-size:11px;}Theshape-renderingpropertyisanSVGattribute,usedheretomakesureouraxisanditstickmarklinesarepixel-perfect.Noblurryaxesforus!通过定义坐标轴所在的g容器样式,来控制坐标轴外观。上面对g容器使用的css样式axis。坐标轴效果如下:.axisline{fill:none;‘无填充stroke:black;‘黑色shape-rendering:crispEdges;}.axistext{font-family:sans-serif;字体font-size:11px;‘字体大小}That’sbetter,butthetopoftheaxisiscutoff,andwewantitdownatthebasethechartanyway.Wecantransformtheentireaxisgroup,pushingittothebottom:通过上面的调整,位于顶部的坐标轴看不到了,被截掉了。我们把坐标轴放到最下面。这里有两个问题:1、为什么坐标轴设置为bottom,确定顶部。2、为什么第二次设置后,被截掉了,而重新设置后,就看到了。svg.append(g).attr(class,axis).attr(transform,translate(0,+(h-padding)+)).call(xAxis);Notetheuseof(h-padding),sothegroup’stopedgeissettoh,theheightoftheentireimage,minusthepaddingvaluewecreatedearlier.SVG的原点在左上角,所以对于SVG的bottom在上面?原SVG的位置在0,现在要转到SVG图像的下面,在上一文章中,SVG图像中散点的显示范围是cy在padding~h-padding之间,我们把x轴从上面的0移动到下面的h-padding位置。Muchbetter!Here’sthecodesofar.CheckforTicksSometicksspreaddisease,butD3’stickscommunicateinformation.Yetmoreticksarenotnecessarilybetter,andatacertainpointtheybegintoclutteryourchart.You’llnoticethatweneverspecifiedhowmanytickstoincludeontheaxis,noratwhatintervalstheyshouldappear.Withoutclearinstruction,D3hasauto-magicallyexaminedourscalexScaleandmadeinformedjudgementsabouthowmanytickstoinclude,andatwhatintervals(every50,inthiscase).过多的坐标轴刻度会使你的图标显得凌乱。你会注意到我们从不指定在坐标轴上需要有多少刻度,或者刻度直接间隔多少。D3自动的对我们的xScale参数进行判断并决定该坐标轴上究竟需要多少刻度。Asyouwouldimagine,youcancustomizeallaspectsofyouraxes,startingwiththeroughnumberofticks,usingticks():varxAxis=d3.svg.axis().scale(xScale).orient(bottom).ticks(5);//Setrough#ofticksHere’sthatcode.Youprobablynoticedthat,whilewespecifiedonlyfiveticks,D3hasmadeanexecutivedecisionandorderedupatotalo
本文标题:PMOD3应用注释_D3_C08Tutorials_16_Axes_使用D3添加坐标轴
链接地址:https://www.777doc.com/doc-2851738 .html