晴明的博客园 GitHub      CodePen      CodeWars     

[svg] D3.js (2)

SVG 形状

d3.svg.arc()

构造一个新的弧生成器,使用默认的内半径、外半径、开始弧度和
结束弧度访问器(假定输入数据是包含匹配于访问器的命名属性的对象);
而默认的访问器假定弧的尺寸是动态指定的,当然设置一个或多个的尺寸为常量也是很常见的,
例如饼图的内半径设为0;返回的函数为封闭的实心弧度生成路径数据,如饼图或环图。

事实上,有四种可能性:
圆disk(内半径为0,角度跨度大于等于2π),
扇形circular sector(内半径为0,角度跨度小于2π),
环形 annulus(内半径大于0,角度跨度为2π),
以及环形扇区(annular sector)(内半径大于0,并且角度跨度小于2π)。

arc(datum[, index])

为指定的datum参数返回路径数据字符串。
可选参数index 可能会指定,传递给弧度访问器函数。

arc.innerRadius([radius])

通常情况下,指定内半径访问器是由于:
输入数据是不同的格式、或你想要应用比例尺,亦或你想为圆环指定个恒定的内半径。
内半径访问器会像D3的其他函数一样被调用;
函数中的this代表选择中的当前元素(技术上来说,this上下文调用弧函数;
然而一般情况下,弧生成器传递给attr操作符, this上下文将关联DOM元素);
函数传递两个参数:当前数据d和索引i;
当然,也可以指定其为一个常数而不是函数。
默认访问器假定输入数据是带有适当命名属性的对象:

function innerRadius(d) {
  return d.innerRadius;
}

arc.outerRadius([radius])

通常情况下,指定外半径访问器是由于:输入数据是不同的格式、或你想要应用比例尺,
亦或你想为圆环指定个恒定的外半径。
外半径访问器会像D3的其他函数一样被调用;
函数中的this代表选择中的当前元素(技术上来说,this上下文调用弧函数;
然而一般情况下,弧生成器传递给attr操作符, this上下文将关联DOM元素);
函数传递两个参数:当前数据d和索引i;
当然,也可以指定其为一个常数而不是函数;
默认访问器假定输入数据是带有适当命名属性的对象:

function outerRadius(d) {
  return d.outerRadius;
}

arc.startAngle([angle])

如果指定angle,则设置开始角度访问器startAngle-accessor为指定的函数或常数,
如果未指定,则返回当前的访问器;默认访问器假定输入数据是带有适当命名属性的对象:

function startAngle(d) {
  return d.startAngle;
}

角度使用弧度radians表示,尽管SVG中使用的是角度;

起始角度为0即对应12点钟的指针方向,
起始方向为顺时钟方向;

(90 / 360) * 2 * Math.PI  顺时钟旋转90度
(180 / 360) * 2 * Math.PI  顺时钟旋转180度

(-90 / 360) * 2 * Math.PI  逆时钟旋转90度
(-180 / 360) * 2 * Math.PI  逆时钟旋转180度

访问器参数(通常为d和i)和this指针传递给弧生成器时调用。

为了构建饼图和环图,需要计算每个弧的起始角度和上个弧的结束角度;
使用饼布局 pie layout会非常方便的,即类似于堆叠布局stack;给定一组输入数据,
饼布局会调用弧对象来生成开始弧度和结束弧度属性( startAngle and endAngle),
你也可以使用默认的弧访问器。
开始角度访问器startAngle-accessor会像D3的其他函数一样被调用;
函数传递两个参数:当前数据d和索引i;
当然,也可以指定其为一个常数。

arc.endAngle([angle])

如果指定angle,则设置开始角度访问器endAngle-accessor为指定的函数或常数,
如果未指定,则返回当前的访问器;
角度使用弧度radians表示,尽管SVG中使用的是角度;
访问器会以传递给弧度生成器的参数形式被调用;
默认访问器假定输入数据是包含适当命名属性的对象:

function endAngle(d) {
  return d.endAngle;
}

为了构建饼图和环图,需要计算每个弧的起始角度和上个弧的结束角度;
这保证了你会非常方便的使用饼布局 pie layout,即类似于堆叠布局stack;
给定一组数据,饼布局会调用弧对象来生成开始弧度和结束弧度属性,
你也可以使用默认的弧访问器。
开始角度访问器endAngle-accessor会像D3的其他函数一样被调用;
函数传递两个参数:当前数据d和索引i;当然,也可以指定其为一个常数。

d3.svg.area()

构造一个新的面积生成器,使用默认的x(横坐标),y0(基线),
y1(顶线)访问器函数(假定输入数据是一个双元素数字数组,详见下文)和线性插值器。
对于分段线性曲线,或多边形,返回的函数生成一个封闭的path数据。

从概念上讲,多边形的形成是通过使用两条线(lines):
顶线的形成是通过x(横坐标)和y1(顶线)访问器方法,从左至右生成。
底线是添加到这一条线上,使用x (横坐标)和y0(基线)访问器方法,从右到左去生成。
通过将转换属性(transform)设置为旋转path元素90度,
您还可以生成垂直的面积图。通过改变插值,还可以生成splines和台step函数。

区域生成器被设计为与线生成器(line)一起使用的。
例如,当生成区域图表时,可能用一个带有填充样式的区域生成器和一个带有描边样式的线生成器,
此描边样式可以使区域的顶部边缘更加突出显示。
由于区域生成器只可以用于设置d属性,
所以可以通过使用标准的SVG样式和属性去控制区域的外观,
例如填充样式fill。

创建streamgraphs (堆叠区域图),使用stack(叠层)布局。
此布局可以为一个系列中的每个值去设置y0属性,
这个系列值可从y0(基线),y1(顶线)访问器中使用。
注意,每个系列中必须有相同数量的值,并且每个值必须有相同的x横坐标;
如果你在每系列里有缺失数据或不一致的x横坐标,那么在计算叠层布局之前,
你必须重新取样和插入你的数据。

area(data)

对于指定的数据元素数组data,返回路径(path)数据字符串;当路径是空的时候返回null。

area.x([x])

如果指定了x参数,设置x(横坐标)访问器为指定的方法或常量。
如果没有指定x,返回当前x访问器。为传递给区域生成器的数据数组中的每个元素,调用该访问器。默认访问器中假定每个输入元素是双元素数字数组:

function x(d) {
  return d[0];
}

通常情况下,x访问器被指定是因为输入数据是不同格式的,或者因为你想应用一个比例尺。
例如,如果你的数据被指定为一个带有x和y属性的对象,而不是一个元组,
那么你可能会引用这些属性同时应用比例尺:

var x = d3.scale.linear().range([0, w]),
    y = d3.scale.linear().range([h, 0]);

var area = d3.svg.area()
    .x(function(d) { return x(d.x); })
    .y0(h)
    .y1(function(d) { return y(d.y); });

x访问器会和D3中其他值函数一样的方式被调用。
函数中的this上下文就是选择中的当前元素。
(从技术上讲,相同的this上下文调用区域函数;
然而,通常情况下,区域生成器被传递到attr操作符,this上下文将会被关联到DOM元素上)。
函数被传递两个参数,当前的数据(d)和当前的索引值(i)。
在this上下文中,索引值就是控制数据点的数组中的索引,而不是当前选择元素的索引。
x访问器在每一个数据中按照数据数组指定的顺序被恰好调用一次。
因此,可以指定一个不确定的访问器,例如随机数生成器。
也可以指定x访问器为一个常量,而不是一个函数,
在这种情况下,所有的点将有相同的横坐标值。

area.x0([x0])

获取或设置x0-坐标(基线)访问器。

area.x1([x1])

获取或设置x1-坐标(顶线)访问器。

area.y([y])

获取或设置y-坐标访问器。

area.y0([y0])

如果y0被指定,y0(基线)访问器为指定的方法或常量。
如果没有指定y0,返回当前y0(基线)访问器。
将为传递给区域生成器数据数组中的每个元素,调用该访问器函数。
默认的访问器是常量0,也就是使用一个固定的基线y = 0。
对于如何指定一个y0(基线)访问器的例子,看类似的x访问器。

area.y1([y1])

如果指定参数y1 ,y1访问器为指定的方法或常量。
如果没有指定y1,就会返回当前的y1访问器。
将为传递给区域生成器数据数组中的每个元素,调用该访问器函数。
默认的访问器假定每个输入元素是一个双元素的数字数组:

function y1(d) {
  return d[1];
}

关于如何指定一个y1(顶线)访问器的一个例子,请看类似的x访问器。
注意,像大多数其他的图形库,SVG使用顶部-左侧作为原点,
因此更高的数值y将会在屏幕更低的位置。
对于可视化而言,我们通常希望原点是位于底部-左侧的位置。
可以做到这一点的一个简单的方法便是转化y比例尺的范围,
即通过使用范围([h,0])而不是范围([0,h])。

area.interpolate([interpolate])

如果指定插值器interpolate,便设置插值器模式为指定的字符串或函数。
如果没有指定插值器interpolate,返回当前插值器模式。
插值器模式支持以下命名:

    linear(线性):分段的线性片段,如折线。
    step(步):水平和垂直片段之间交替,如台阶函数。
    step-before:垂直和水平片段之间交替,如台阶函数。
    step-after: 水平和垂直片段之间交替,如台阶函数。
    basis :一个B-spline,在末尾控制点的重复。
    basis-open :一个开放的B-spline;首尾不相交。
    cardinal :一个Cardinal spline,在末尾控制点的重复。
    cardinal-open:一个开放的Cardinal spline;首尾不相交,但是会和其他控制点相交。
    monotone -立方插值(cubic interpolation)保存y值得单调性。

其中一些插值模式的行为通过指定的张力(tension)可能被进一步自定义。
从技术上讲,同样也会支持basis-closed和 cardinal-closed的插值模式,
但这些模式应用在一条线上比应用在一个区域上更有意义。

如果参数interpolate是一个函数,
那么这个函数将被调用去转换一个形式为[[x0, y0], [x1, y1], …]的数组,
返回一个SVG路径数据字符串(SVG path data string),它将用于显示区域。
字符串起始位置的“M”是隐含的,不会被返回。
例如,线性插值的实现为:

function interpolateLinear(points) {
  return points.join("L");
}

这等效于(并更加高效):

function interpolateLinear(points) {
  var path = "";
  for (var i = 0; i < points.length; i++) {
    if (i) path += "L";
    path += points[i][0] + "," + points[i][1];
  }
  return path;
}

路径数据生成器

为了简化路径元素的d属性的构造,D3包含很多辅助类用来生成路径数据。
如果你的数据是xy坐标序列,你可以定义访问器函数,然后用路径生成器制造路径数据。
例如:

var line = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis");

然后,你可以使用下面函数设置d属性:

g.append("path")
    .attr("d", line);

不论数据是否绑定到 g 元素(在这个例子中)都将传递给 line 实例。
这样,数据必须指定为一个数组。
对于数据数组中的每个元素,x和y访问器函数用来抽出控制点坐标。

路径生成器,例如d3.svg.line返回的既是一个函数又是一个对象。
这样,你就可以像其他函数一样调用生成器了。
并且生成器还有额外的方法来改变它的行为。
像D3中的其他类一样,路径生成器遵循方法链模式其中的setter方法返回生成器自身。
允许在一个简单的声明中调用多个setter方法。

svg:line x1="0" y1="0" x2="0" y2="0"

直线元素line定义线段始于一个点而终止于另一个点。
第一个点使用x1和y1属性指定,第二个点使用x2和y2属性指定。
线元素常用来画规则,参考线,轴和刻度线。

d3.svg.line()

构造一个新的线生成器使用默认的x和y访问器函数(假设输入数据是一个两元素数字数组),
和线性插值器。
返回的函数生成路径数组为开口分段线性曲线,折线或者,如折线图

通过改变插值器,可以生成样条线以及步长函数。
另外,不要害怕最后粘上其他路径命令。
例如,如果想生成一个封闭的路径,追加closepath (Z)命令:

g.append("path")
    .attr("d", function(d) { return line(d) + "Z"; });

线生成器设计来和面积生成器(area)一起使用。
例如,当生成面积图时,你可能使用带有填充属性的面积生成器,
以及带有描边属性的线生成器来突出面积的上边缘。
当线生成器只是用来设置d属性,你可以使用SVG样式和属性控制线的展示,
例如fill,stroke和stroke-width。

line(data)

为指定的data元素数组返回路径数据字符串,如果路径是空则返回null。

line.x([x])

如果指定了x,为指定的函数或常量设置x访问器。
如果x没有指定,返回当前的x访问器。
这个访问器为传递给x线生成器的数据数组中的每个元素。
默认的访问器假设每个输入的元素是一个二元素数字数组:

function x(d) {
  return d[0];
}

通常,一个x访问器是指定的,因为输入数据是不同格式的,
或者因为你想使用比例尺(数值比例尺)。例如,如果你的数据指定为一个含有x,y属性的的对象,
而不是一个元组,你可以反引用这些属性同时应用比例尺:

var x = d3.scale.linear().range([0, w]),
    y = d3.scale.linear().range([h, 0]);

var line = d3.svg.line()
    .x(function(d) { return x(d.x); })
    .y(function(d) { return y(d.y); });

x访问器像D3中其他值函数一样的方式调用。
函数的this上下文就是选择中的当前元素(通常,相同的this上下文调用线函数;
然而,在通常情况下线生成器传递给attr操作符,this上下文将关联DOM元素)。
函数传入两个入参当前的数据d和当前的索引i。
this上下文,索引就是控制点中的索引,而不是选择中当前元素的索引。
x访问器按照数据数组中指定的顺序,每个元素恰好调用一次。
这样,就可能指定不确定性访问器,例如随机数生成器。
也可以指定x访问器为一个常量而不是函数,在所有点都有相同的x坐标情况下。

line.y([y])

如果指定了y,为指定的函数或常量设置y访问器。
如果y没有指定,返回当前的y访问器。
这个访问器为传递给y线生成器的数据数组中的每个元素。
默认的访问器假设每个输入的元素是一个二元素数字数组:

function y(d) {
  return d[1];
}

怎样指定一个y访问器,参见相似的x访问器。
注意:像所有的其他图形库,SVG使用左上角作为原点。
这样在屏幕中较高的y值就更低。
对于可视化我们常常想要原点是在左下角。
一个简单的方法实现这个可以使用range([h, 0])替代range([0, h])反转y比例尺的范围。

line.interpolate([interpolate])

如果指定了interpolate 参数,就会设置插值器模式为指定的字符串或者函数。
如果没有指定,就返回当前的插值器模式。

支持下面的命名插值器模式:

    linear -分段线性片段,如折线。
    linear-closed –闭合直线段,以形成一个多边形。
    step - 水平和垂直段之间交替,如在step函数中。
    step-before -垂直和水平段之间交替,如在step函数中。
    step-after -水平和垂直段之间交替,如在step函数中。
    basis - B样条曲线(B-spline),在两端的控制点的重复。
    basis-open – 开放B样条曲线,首尾不会相交。
    basis-closed -封闭B样条曲线,如在一个循环。
    bundle – 等价于basis, 除了使用tension参数拉直样条曲线。
    cardinal – 基本样条曲线(Cardinal spline),在末端控制点的重复。
    cardinal-open –开放的基本样条曲线,首尾不会相交,但和其他控制点相交。
    cardinal-closed -封闭基本样条曲线,如在一个循环。
    monotone - 三次插值(cubic interpolation),可以保留y的单调性。

其中一些插值模式的行为可能通过指定的张力tension进行进一步定制。

如果interpolate 是一个函数,
然后这个函数将被调用来反转一个形如[[x0, y0], [x1, y1], …]的点数组,
返回一个SVG路径数据字符串(SVG path data string),用来展示线。
字符串开始处的“M” 隐含的,不应该被返回。

例如,线性插值被实现为:

function interpolateLinear(points) {
  return points.join("L");
}

这相当于(并且比这更有效):

function interpolateLinear(points) {
  var path = "";
  for (var i = 0; i < points.length; i++) {
    if (i) path += "L";
    path += points[i][0] + "," + points[i][1];
  }
  return path;
}

area.tension([tension])

如果指定张力tension,便将基数样条(Cardinal spline)插值张力(tension)设置为指定区间[0,1]内的数字。
如果没有指定张力tension,返回当前的张力值。
张力值只会影响基本插值模式:cardinal,cardinal-open 和cardinal-closed。
默认的张力值是0.7。在某种意义上,这可以解释为切线长度;
值1将产生零切线,值0将产生一个Catmull-Rom spline。
注意,张力值必须指定为一个常数,而不是一个函数,因为它是整个区域的常数。

Symbols

Symbols provide a categorical shape encoding as is commonly used in scatterplots.
Symbols are always centered at (0,0);
use a transform (see: SVG, Canvas) to move the arc to a different position.

d3.symbol()

Constructs a new symbol generator with the default settings.

symbol(arguments…)

Generates a symbol for the given arguments.
The arguments are arbitrary;
they are simply propagated to the symbol generator’s accessor functions along with the this object.
For example, with the default settings,
no arguments are needed to produce a circle with area 64 square pixels.
If the symbol generator has a context,
then the symbol is rendered to this context as a sequence of path method calls and this function returns void.
Otherwise, a path data string is returned.

symbol.type([type])

symbol types:

circle, cross, diamond, square, star, triangle, and wye.

If type is specified,
sets the symbol type to the specified function or symbol type and returns this line generator. If type is not specified,
returns the current symbol type accessor,

which defaults to:

function type() {
  return circle;
}

布局

d3.layout.stack()

构造一个新的默认的堆叠布局。

Constructs a new stack layout with the default offset (zero) and order (null).
The returned layout object is both an object and a function.
That is: you can call the layout like any other function,
and the layout has additional methods that change its behavior.
Like other classes in D3,
layouts follow the method chaining pattern where setter methods return the layout itself,
allowing multiple setters to be invoked in a concise statement.

stack.offset([offset])

指定整体的基线算法。

If offset is specified, sets the stack offset algorithm to the specified value.
If offset is not specified,
returns the current offset algorithm. The following string values are supported:

    silhouette - center the stream, as in ThemeRiver.
    wiggle - minimize weighted change in slope.
    expand - normalize layers to fill the range [0,1].
    zero - use a zero baseline, i.e., the y-axis.

In addition to a string, offset may be specified as a function.
The input to the offset function is the layer data,
converted to a standardized representation:
a two-dimensional array of values,
where each value is represented as a two-element array [x, y].
The return value of the offset function must be an array of values which represents the y-coordinates of the baseline.
For example,
the default "zero" offset is implemented as:

function offset(data) {
  var j = -1,
      m = data[0].length,
      y0 = [];
  while (++j < m) y0[j] = 0;
  return y0;
}

d3.layout.pack()

用递归的圆-包生成一个层次布局。

Creates a new pack layout with the default settings:
the default sort order is by ascending value;
the default children accessor assumes each input data is an object with a children array;
the default size is 1×1.

pack(root)

pack.nodes的别名。

pack.nodes(root)

计算包布局并返回节点数组。

Runs the pack layout,
returning the array of nodes associated with the specified root node.
The cluster layout is part of D3's family of hierarchical layouts.
These layouts follow the same basic structure:
the input argument to the layout is the root node of the hierarchy,
and the output return value is an array representing the computed positions of all nodes.
Several attributes are populated on each node:

    parent - the parent node, or null for the root.
    children - the array of child nodes, or null for leaf nodes.
    value - the node value, as returned by the value accessor.
    depth - the depth of the node, starting at 0 for the root.
    x - the computed x-coordinate of the node position.
    y - the computed y-coordinate of the node position.
    r - the computed node radius.

pack.value([value])

取得或设置用于圆尺寸的值访问器。

If value is specified,
sets the value accessor to the specified function.
If value is not specified, returns the current value accessor,
which assumes that the input data is an object with a numeric value attribute:

function value(d) {
  return d.value;
}

The value accessor is invoked for each input data element,
and must return a number representing the numeric value of the node.
This value is used to set the area of each circle proportionally to the value.
However, note that circle size is strictly comparable only between leaf nodes;
internal nodes cannot be compared accurately,
as there is empty space between packed child circles and their parent.

pack.size([size])

指定布局尺寸。

If size is specified,
sets the available layout size to the specified two-element array of numbers representing x and y.
If size is not specified,
returns the current size,
which defaults to 1×1.

d3.layout.pie()

构造一个新的默认的饼布局。

Constructs a new pie function with the default value accessor (number),
sort comparator (descending value),
start angle (0) and end angle (2π).
The returned layout object is both an object and a function.
That is: you can call the layout like any other function,
and the layout has additional methods that change its behavior.
Like other classes in D3,
layouts follow the method chaining pattern where setter methods return the layout itself,
allowing multiple setters to be invoked in a concise statement.

pie.value([accessor])

取得或设置值访问器函数。

Specifies how to extract a value from the associated data (e.g. sets the accessor function for the pie layout to use);
accessor is a function which is invoked on each input value passed to pie,
equivalent to calling values.map(accessor) before computing the pie layout.
The function is passed two arguments:
the current datum and the current index.
The default value function is the built-in Number,
which is similar to the identity function.
If accessor is not specified,
returns the current value accessor.

pie.sort([comparator])

控制饼片段的顺时针方向的顺序。

If comparator is specified,
sets the sort order of data for the layout using the specified comparator function.
Pass null to disable sorting.
If comparator is not specified,
returns the current sort order.
The sort order defaults to descending value.
Sorting preserves the index (and z-index) of input values,
affecting only the computed angles.
The comparator function is invoked for pairs of data elements from the values array passed to pie.
Comparator functions may also be implemented using d3.ascending or d3.descending.

d3.svg.diagonal()

使用默认的配置构造一个对角线生成器;
返回值可以用来当做函数使用来生成三次贝塞尔曲线数据,
该曲线的若干条切线可以保证节点连接处会有平滑的介入效.

虽然对角线生成器默认是笛卡尔(轴对齐)的定位方式,
但依然可以自定义 projection 来生成径向或其他任意定位方式的路径数据。

diagonal(datum[, index])

根据指定的 datum 数据参数,生成 path 的路径数据字符串;
一个可选的 index 参数,会传递给对角线生成器的函数。

diagonal.projection([projection])

如果指定了 projection 参数,则设置投影函数为 projection;
如果未指定,则返回当前的投影函数;
投影函数会转换形如 { x, y } 的坐标系统为 [x, y];
默认的投影函数形如:

function projection(d) {
  return [d.x, d.y];
}

默认的投影函数兼容 D3 的大部分布局,
包括:tree、partition、cluster;
例如,一个生成径向对角线的方式如下:

function projection(d) {
  var r = d.y, a = (d.x - 90) / 180 * Math.PI;
  return [r * Math.cos(a), r * Math.sin(a)];
}

投影函数的调用类似于 D3 中其他的大多数函数调用;
函数的两个入参:
d 指向了当前 DOM 所绑定的数据(source 或者 target)、
i 表示当前 DOM 所在的 DOM 树的索引。

d3.layout.tree()

整齐地排列树节点。

Creates a new tree layout with the default settings:
the default sort order is null;
the default children accessor assumes each input data is an object with a children array;
the default separation function uses one node width for siblings,
and two node widths for non-siblings;
the default size is 1×1.

tree(root)

tree.nodes的别名。

tree.nodes(root)

计算父布局并返回一组节点。

Runs the tree layout,
returning the array of nodes associated with the specified root node.
The tree layout is part of D3's family of hierarchical layouts.
These layouts follow the same basic structure:
the input argument to the layout is the root node of the hierarchy, and the output return value is an array representing the computed positions of all nodes.
Several attributes are populated on each node:

    parent - the parent node, or null for the root.
    children - the array of child nodes, or null for leaf nodes.
    depth - the depth of the node, starting at 0 for the root.
    x - the computed x-coordinate of the node position.
    y - the computed y-coordinate of the node position.

Although the layout has a size in x and y,
this represents an arbitrary coordinate system;
for example,
you can treat x as a radius and y as an angle to produce a radial rather than Cartesian layout.

tree.links(nodes)

计算树节点的父-子连接。

Given the specified array of nodes,
such as those returned by nodes,
returns an array of objects representing the links from parent to child for each node.
Leaf nodes will not have any links.
Each link is an object with two attributes:

    source - the parent node (as described above).
    target - the child node.

This method is useful for retrieving a set of link descriptions suitable for display,
often in conjunction with the diagonal shape generator.

For example:

svg.selectAll("path")
    .data(tree.links(nodes))
  .enter().append("path")
    .attr("d", d3.svg.diagonal());

d3.layout.treemap()

使用空间递归分区算法展示树的节点。

Creates a new treemap layout with the default settings:
the default sort order is by descending value;
the default value accessor assumes each input data is an object with a numeric value attribute; the default children accessor assumes each input data is an object with a children array; the default size is 1×1.

treemap(root)

treemap.nodes(root)

计算矩形树布局并返回节点数组。

Runs the treemap layout,
returning the array of nodes associated with the specified root node.
The treemap layout is part of D3's family of hierarchical layouts.
These layouts follow the same basic structure:
the input argument to the layout is the root node of the hierarchy,
and the output return value is an array representing the computed positions of all nodes.
Several attributes are populated on each node:

   parent - the parent node, or null for the root.
   children - the array of child nodes, or null for leaf nodes.
   value - the node value, as returned by the value accessor.
   depth - the depth of the node, starting at 0 for the root.
   area - the computed pixel area of this node. (TODO: remove?)
   x - the minimum x-coordinate of the node position.
   y - the minimum y-coordinate of the node position.
   z - the orientation of this cell’s subdivision, if any. (TODO: remove?)
   dx - the x-extent of the node position.
   dy - the y-extent of the node position.

Note that this will modify the nodes that you pass in!

Although the layout has a size in x and y,
this represents an arbitrary coordinate system;
for example,
you can treat x as a radius and y as an angle to produce a radial rather than Cartesian layout.
In Cartesian orientation, x, y, dx and dy correspond to the "x", "y",
"width" and "height" attributes of the SVG rect element.

treemap.value([value])

取得或设置用来指定矩形树中矩形单元尺寸的值访问器。

If value is specified,
sets the value accessor to the specified function.
If value is not specified,
returns the current value accessor,
which assumes that the input data is an object with a numeric value attribute:

function value(d) {
  return d.value;
}

The value accessor is invoked for each input data element,
and must return a number representing the numeric value of the node.
This value is used to set the area of each node proportionally to the value.

treemap.size([size])

指定布局的尺寸。

If size is specified,
sets the available layout size to the specified two-element array of numbers representing x and y.
If size is not specified,
returns the current size,
which defaults to 1×1.

treemap.round([round])

启用或者禁用四舍五入像素值。

If round is specified,
sets whether or not the treemap layout will round to exact pixel boundaries.
This can be nice to avoid antialiasing artifacts in SVG.
If round is not specified,
returns whether the treemap will be rounded.

treemap.sticky([sticky])

让布局对稳定的更新是粘滞的(sticky)。

If sticky is specified,
sets whether or not the treemap layout is "sticky":
a sticky treemap layout will preserve the relative arrangement of nodes across transitions. The allocation of nodes into squarified horizontal and vertical rows is persisted across updates by storing a z attribute on the last element in each row; this allows nodes to be resized smoothly,
without shuffling or occlusion that would impede perception of changing values.
Note, however, that this results in a suboptimal layout for one of the two states.
If sticky is not specified, returns whether the treemap layout is sticky.

Implementation note: sticky treemaps cache the array of nodes internally;
therefore, it is not possible to reuse the same layout instance on multiple datasets.
To reset the cached state when switching datasets with a sticky layout,
call sticky(true) again.
Since version 1.25.0,
hierarchy layouts no longer copy the input data by default on each invocation,
so it may be possible to eliminate caching and make the layout fully stateless.

行为

d3.behavior.drag()

创建拖动行为。

Constructs a new drag behavior.
Once constructed,
you can apply the drag behavior to selected elements using selection.call:

var drag = d3.behavior.drag();
selection.call(drag);

All registered listeners use the “drag” namespace,
so to subsequently remove the behavior:

selection.on(".drag", null);

drag.on(type[, listener])

监听拖动事件。

Registers the specified listener to receive events of the specified type from the drag behavior.
If no listener is specified,
returns the currently-registered listener for the specified event type.
(The type may include a namespace; see dispatch.on for additional details.)
The following events are supported:

    dragstart - when a drag gesture starts.
    drag - when the drag gesture moves.
    dragend - when the drag gesture finishes.

Drag events (but not dragstart and dragend events) expose "x" and "y" properties representing the current position of the drag gesture in local coordinates.
By default, this position is simply the mouse (or touch) position;
however, the position can be modified by specifying an origin.
The drag event also exposes "dx" and "dy" properties representing the element’s coordinates relative to its position at the beginning of the gesture,
which is occasionally more convenient than specifying an explicit origin.

During a drag gesture,
some browser default behaviors (such as text selection) are prevented.
To allow the dragging of links,
the default behavior for a click event that immediately follows a non-empty drag gesture is prevented.
When registering your own click listener on draggable elements,
you can check whether the click event was suppressed as follows:

selection.on("click", function() {
  if (d3.event.defaultPrevented) return; // click suppressed
  console.log("clicked!");
});

When combining drag behaviors with other event listeners for interaction events (such as having drag take precedence over zoom),
you may also consider stopping propagation on the source event to prevent multiple actions:

drag.on("dragstart", function() {
  d3.event.sourceEvent.stopPropagation(); // silence other listeners
});

d3.behavior.zoom()

创建缩放行为。

Constructs a new zoom behavior.
Once constructed,
you can apply the behavior to selected elements using selection.call:

var zoom = d3.behavior.zoom();
selection.call(zoom);

All registered listeners use the “zoom” namespace,
so to subsequently remove the behavior:

selection.on(".zoom", null);

zoom(selection)

给指定的元素应用缩放行为。

Applies the zoom behavior to the specified selection,
registering the necessary event listeners to support panning and zooming.

zoom.translate([translate])

当前的平移偏移量。

Specifies the current zoom translation vector.
If not specified,
returns the current translation vector,
which defaults to [0, 0].

zoom.scale([scale])

当前的比例因子。

Specifies the current zoom scale.
If not specified, returns the current zoom scale, which defaults to 1.

zoom.scaleExtent([extent])

可选参数,比例因子范围。

Specifies the zoom scale's allowed range as a two-element array,
[minimum, maximum].
If not specified,
returns the current scale extent,
which defaults to [0, Infinity].

zoom.on(type, listener)

事件监听器。

Registers the specified listener to receive events of the specified type from the zoom behavior.
The following types are supported:

    zoomstart - at the start of a zoom gesture (e.g., touchstart).
    zoom - when the view changes (e.g., touchmove).
    zoomend - at the end of the current zoom gesture (e.g., touchend).

If an event listener was already registered for the same type,
the existing listener is removed before the new listener is added.
To register multiple listeners for the same event type,
the type may be followed by an optional namespace,
such as "zoom.foo" and "zoom.bar".
To remove a listener, pass null as the listener.

For mousewheel events,
which happen discretely with no explicit start and end reported by the browser,
events that occur within 50 milliseconds of each other are grouped into a single zoom gesture.
If you want more robust interpretation of these gestures,
please petition your browser vendor of choice for better touch event support.

When fired, the d3.event object will contain the following properties:

    scale - a number; the current scale.
    translate - a two-element array representing the current translation vector.

d3.layout.force()

使用物理模拟排放链接节点的位置。

Constructs a new force-directed layout with the default settings:
size 1×1, link strength 1, friction 0.9, distance 20, charge strength -30,
gravity strength 0.1, and theta parameter 0.8.
The default nodes and links are the empty array,
and when the layout is started, the internal alpha cooling parameter is set to 0.1.
The general pattern for constructing force-directed layouts is to set all the configuration properties,
and then call start:

var force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .size([w, h])
    .linkStrength(0.1)
    .friction(0.9)
    .linkDistance(20)
    .charge(-30)
    .gravity(0.1)
    .theta(0.8)
    .alpha(0.1)
    .start();

Note that, like D3's other layouts,
the force-directed layout doesn't mandate a particular visual representation.
Most commonly, nodes are mapped to SVG circle elements,
and links are mapped to SVG line elements.
But you might also display nodes as symbols or images.

force.nodes([nodes])

取得或者设置布局的节点数组。

If nodes is specified,
sets the layout's associated nodes to the specified array.
If nodes is not specified, returns the current array,
which defaults to the empty array.

Each node has the following attributes:

    index - the zero-based index of the node within the nodes array.
    x - the x-coordinate of the current node position.
    y - the y-coordinate of the current node position.
    px - the x-coordinate of the previous node position.
    py - the y-coordinate of the previous node position.
    fixed - a boolean indicating whether node position is locked.
    weight - the node weight; the number of associated links.

These attributes do not need to be set before passing the nodes to the layout;
if they are not set,
suitable defaults will be initialized by the layout when start is called.
However, be aware that if you are storing other data on your nodes,
your data attributes should not conflict with the above properties used by the layout.

取得或者设置节点间的链接数组。

If links is specified,
sets the layout's associated links to the specified array.
If links is not specified, returns the current array,
which defaults to the empty array.
Each link has the following attributes:

    source - the source node (an element in nodes).
    target - the target node (an element in nodes).

Note: the values of the source and target attributes may be initially specified as indexes into the nodes array;
these will be replaced by references after the call to start.
Link objects may have additional fields that you specify;
this data can be used to compute link strength and distance on a per-link basis using an accessor function.

force.start()

当节点变化时启动或者重启模拟。

Starts the simulation;
this method must be called when the layout is first created,
after assigning the nodes and links.
In addition, it should be called again whenever the nodes or links change.
Internally,
the layout uses a cooling parameter alpha which controls the layout temperature:
as the physical simulation converges on a stable layout,
the temperature drops,
causing nodes to move more slowly.
Eventually,
alpha drops below a threshold and the simulation stops completely,
freeing the CPU and avoiding battery drain.
The layout can be reheated using resume or by restarting;
this happens automatically when using the drag behavior.

On start,
the layout initializes various attributes on the associated nodes.
The index of each node is computed by iterating over the array,
starting at zero. The initial x and y coordinates,
if not already set externally to a valid number,
are computed by examining neighboring nodes:
if a linked node already has an initial position in x or y,
the corresponding coordinates are applied to the new node.
This increases the stability of the graph layout when new nodes are added,
rather than using the default which is to initialize the position randomly within the layout's size.
The previous px and py position is set to the initial position,
if not already set,
giving new nodes an initial velocity of zero.
Finally, the fixed boolean defaults to false.

The layout also initializes the source and target attributes on the associated links:
for convenience,
these attributes may be specified as a numeric index rather than a direct link,
such that the nodes and links can be read-in from a JSON file or other static description that may not allow circular linking.
The source and target attributes on incoming links are only replaced with the corresponding entries in nodes if these attributes are numbers;
thus,
these attributes on existing links are unaffected when the layout is restarted.
The link distances and strengths are also computed on start.

force.tick()

运行布局模拟的一步。

Runs the force layout simulation one step.
This method can be used in conjunction with start and stop to compute a static layout.
For example:

force.start();
for (var i = 0; i < n; ++i) force.tick();
force.stop();

The number of iterations depends on the graph size and complexity.
The choice of initial positions can also have a dramatic impact on how quickly the graph converges on a good solution.
For example, here the nodes are arranged along the diagonal:

var n = nodes.length;
nodes.forEach(function(d, i) {
  d.x = d.y = width / n * i;
});

If you do not initialize the positions manually,
the force layout will initialize them randomly,
resulting in somewhat unpredictable behavior.

force.gravity([gravity])

取得或者设置重力强度。

If gravity is specified,
sets the gravitational strength to the specified numerical value.
If gravity is not specified,
returns the current gravitational strength,
which defaults to 0.1. The name of this parameter is perhaps misleading;
it does not correspond to physical gravity (which can be simulated using a positive charge parameter).
Instead,
gravity is implemented as a weak geometric constraint similar to a virtual spring connecting each node to the center of the layout's size.
This approach has nice properties:
near the center of the layout,
the gravitational strength is almost zero,
avoiding any local distortion of the layout;
as nodes get pushed farther away from the center,
the gravitational strength becomes stronger in linear proportion to the distance.
Thus,
gravity will always overcome repulsive charge forces at some threshold,
preventing disconnected nodes from escaping the layout.

Gravity can be disabled by setting the gravitational strength to zero.
If you disable gravity,
it is recommended that you implement some other geometric constraint to prevent nodes from escaping the layout,
such as constraining them within the layout's bounds.

force.charge([charge])

取得或者设置电荷强度。

If charge is specified,
sets the charge strength to the specified value.
If charge is not specified,
returns the current charge strength,
which defaults to -30.
If charge is a constant,
then all nodes have the same charge.
Otherwise, if charge is a function,
then the function is evaluated for each node (in order),
being passed the node and its index,
with the this context as the force layout;
the function's return value is then used to set each node's charge.
The function is evaluated whenever the layout starts.

A negative value results in node repulsion,
while a positive value results in node attraction.
For graph layout,
negative values should be used;
for n-body simulation,
positive values can be used.
All nodes are assumed to be infinitesimal points with equal charge and mass.
Charge forces are implemented efficiently via the Barnes–Hut algorithm, computing a quadtree for each tick. Setting the charge force to zero disables computation of the quadtree, which can noticeably improve performance if you do not need n-body forces.

force.friction([friction])

取得或者设置摩擦系数。

If friction is specified,
sets the friction coefficient to the specified value.
If friction is not specified,
returns the current coefficient, which defaults to 0.9.
The name of this parameter is perhaps misleading;
it does not correspond to a standard physical coefficient of friction.
Instead, it more closely approximates velocity decay:
at each tick of the simulation,
the particle velocity is scaled by the specified friction.
Thus, a value of 1 corresponds to a frictionless environment,
while a value of 0 freezes all particles in place.
Values outside the range [0,1] are not recommended and may have destabilizing effects.

force.linkDistance([distance])

取得或者设置链接距离。

If distance is specified,
sets the target distance between linked nodes to the specified value.
If distance is not specified,
returns the layout's current link distance,
which defaults to 20. If distance is a constant,
then all links are the same distance.
Otherwise, if distance is a function,
then the function is evaluated for each link (in order),
being passed the link and its index,
with the this context as the force layout;
the function's return value is then used to set each link's distance.
The function is evaluated whenever the layout starts.

Links are not implemented as "spring forces",
as is common in other force-directed layouts,
but as weak geometric constraints.
For each tick of the layout,
the distance between each pair of linked nodes is computed and compared to the target distance;
the links are then moved towards each other,
or away from each other,
so as to converge on the desired distance.
This method of constraints relaxation on top of position Verlet integration is vastly more stable than previous methods using spring forces,
and also allows for the flexible implementation of other constraints in the tick event listener,
such as hierarchical layering.

force.linkStrength([strength])

取得或者设置链接强度。

If strength is specified,
sets the strength (rigidity) of links to the specified value in the range [0,1].
If strength is not specified,
returns the layout's current link strength,
which defaults to 1.
If strength is a constant,
then all links have the same strength.
Otherwise, if strength is a function,
then the function is evaluated for each link (in order),
being passed the link and its index,
with the this context as the force layout;
the function's return value is then used to set each link's strength.
The function is evaluated whenever the layout starts.

force.size([width, height])

取得或者设置布局大小。

If size is specified,
sets the available layout size to the specified two-element array of numbers representing x and y.
If size is not specified, returns the current size,
which defaults to [1, 1].
The size affects two aspects of the force-directed layout:
the gravitational center,
and the initial random position.
The center of gravity is simply [ x / 2, y / 2 ].
When nodes are added to the force layout,
if they do not have x and y attributes already set,
then these attributes are initialized using a uniform random distribution in the range [0, x] and [0, y],
respectively.

force.alpha([value])

取得或者设置力布局的冷却参数。

Gets or sets the force layout's cooling parameter, alpha.
If value is specified,
sets alpha to the specified value and returns the force layout.
If value is greater than zero,
this method also restarts the force layout if it is not already running,
dispatching a "start" event and enabling the tick timer.
If value is nonpositive,
and the force layout is running,
this method stops the force layout on the next tick and dispatches an "end" event.
If value is not specified,
this method returns the current alpha value.

force.resume()

重新加热冷却参数,并重启模拟。

Equivalent to:

force.alpha(.1);

Sets the cooling parameter alpha to 0.1.
This method sets the internal alpha parameter to 0.1,
and then restarts the timer.
Typically, you don't need to call this method directly;
it is called automatically by start.
It is also called automatically by drag during a drag gesture.

地理路径

d3.geo.path()

创建一个新的地理路径生成器,使用默认设置:
albersUsa投影和4.5个像素点的半径。

path(feature[, index])

为给定的功能feature返回路径数据串,它可以是任何GeoJSON的特征或几何对象:

    Point –单个位置。
    MultiPoint –一组位置。
    LineString –一组位置形成一条连续的线。
    MultiLineString - 位置数组的数组,形成多条线。
    Polygon –位置数组的数组,形成一个多边形(可能是由小洞组成的)。
    MultiPolygon –位置的多维数组,形成了多个多边形。
    GeometryCollection –几何对象的数组。
    Feature - 包含了几何对象其中的一个特征。
    FeatureCollection –特征对象的数组。

“Sphere”类型也支持,对于绘制地球的轮廓是非常有用的。sphere球体没有坐标。
一个可选的index 索引可以被指定,传递给pointRadius存取器,
Index在路径生成器被selection.attr调用的时候自动地传递。
重要的是:一多边形内部是所有的点,这些点是以顺时针方向围绕着多边形。
如果你的GeoJSON输入有错误顺序的多边形,那么你必须扭转它们,通过ST_ForceRHR,
你也可以将你的GeoJSON转换为TopoJSON,这样的话,它就能自动生成。
显示多个功能,你可以将它们放置在一个单一的特征集和单一路径元素上:

svg.append("path")
.datum({type:"FeatureCollection",features:features})
.attr("d",d3.geo.path());

另外,您也可以创建多个不同的路径元素:

svg.selectAll("path")
.data(features)
.enter().append("path")
.attr("d",d3.geo.path());

对于集合来说利用不同的路径元素通常地比单个路径元素要慢。
但是,如果你想与特征分别进行交互的话,
不同的路径元素是最好的(例如,使用CSS:悬停或单击事件)。

path.projection([projection])

如果 指定了投影projection,设置为路径生成器使用的投影为指定的投影函数。
如果projection 投影没有指定,那么返回当前的投影,默认为albersUsa。
projection 投影通常是D3一个内置地理投影;
然而,任何函数都可以使用。
投影函数采用了两元素的数字数组来代表坐标的位置,[longitude, latitude],
并返回类似的表示该投影像素位置[x, y]的两元素数字数组。
例如,一个基本的spherical Mercator投影:

function mercator(coordinates){
return[
coordinates[0]/360,
(-180/Math.PI*Math.log(Math.tan(Math.PI/4+coordinates[1]*Math.PI/360)))/360
];
}

从内在的说,这个点投影函数是包裹着一个备用的流变换,
它可以执行自适应重采样。然而,备用的流不执行任何裁剪或切割。
为了更好地控制流的变换,
projection 投影可以被指定为一个对象来实现流方法。
该流的方法需要一个输出流作为输入,并返回一个投影在输入的几何体上的包装流,
换句话说,它实现了projection.stream。
如果投影为null,则路径使用恒等变换,
其中输入的几何体不被投影并且不是直接以原始坐标来渲染。
这对已经投影的几何体快速渲染有用,或对正方形投影的快速渲染有用。

posted @ 2016-11-02 19:06  晴明桑  阅读(519)  评论(0编辑  收藏  举报