Skip to content

SVG Shapes

zziuni edited this page Mar 22, 2013 · 61 revisions

WikiAPI ReferenceSVGSVG Shapes

SVG has a number of built-in simple shapes, such as axis-aligned rectangles and circles. For greater flexibility, you can use SVG's path element in conjunction with D3's path data generators. If you're familiar with Protovis, you'll note that D3's path generators are similar to Protovis marks.

A shape generator, such as that returned by d3.svg.arc, is both an object and a function. That is: you can call the shape like any other function, and the shape has additional methods that change its behavior. Like other classes in D3, shapes follow the method chaining pattern where setter methods return the shape itself, allowing multiple setters to be invoked in a concise statement.

SVG Elements

All SVG shapes can be transformed using the transform attribute. You can apply the transform either to the shape directly, or to a containing g element. Thus, when a shape is defined as "axis-aligned", that merely means axis-aligned within the local coordinate system; you can still rotate and otherwise transform the shape. Shapes can be filled and stroked using the fill and stroke styles. (You can also use the attributes of the same name, but styles are recommended as they are compatible with external stylesheets.)

# svg:rect x="0" y="0" width="0" height="0" rx="0" ry="0"

The rect element defines an axis-aligned rectangle. The top-left corner of the rectangle is positioned using the x and y attributes, while its size is specified using width and height. A rounded rectangle can be produced using the optional rx and ry attributes.

# svg:circle cx="0" cy="0" r="0"

The circle element defines a circle based on a center point and a radius. The center is positioned using the cx and cy attributes, while the radius is specified using the r attribute.

# svg:ellipse cx="0" cy="0" rx="0" ry="0"

The ellipse element defines an axis-aligned ellipse based on a center point and two radii. The center is positioned using the cx and cy attributes, while the radii are specified using the rx and ry attributes.

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

The line element defines a line segment that starts at one point and ends at another. The first point is specified using the x1 and y1 attributes, while the second point is specified using the x2 and y2 attributes. The line element is a popular choice for drawing rules, reference lines, axes and tick marks.

# svg:polyline points=""

The polyline element defines a set of connected straight line segments. Typically, polyline elements define open shapes. The points that make up the polyline are specified using the points attribute. Note: in D3, it is typically more convenient and flexible to use the d3.svg.line path generator in conjunction with a path element.

# svg:polygon points=""

The polygon element defines a closed shape consisting of a set of connected straight line segments. The points that make up the polygon are specified using the points attribute. Note: in D3, it is typically more convenient and flexible to use the d3.svg.line path generator in conjunction with a path element. The line can be closed using the closepath "Z" command.

# svg:text x="0" y="0" dx="0" dy="0" text-anchor="start"

The text element defines a graphics element consisting of text. The text content of the text element (see the text operator) define the characters to be rendered. The anchor position of the text element is controlled using the x and y attributes; additionally, the text can be offset from the anchor using dx and dy attributes. This offset is particularly convenient for controlling the text margin and baseline, as you can use "em" units which are relative to the font size. The horizontal text alignment is controlling using the text-anchor attribute. Here are a few examples:

<svg:text text-anchor="start">left-align, bottom-baseline</svg:text>
<svg:text text-anchor="middle">center-align, bottom-baseline</svg:text>
<svg:text text-anchor="end">right-align, bottom-baseline</svg:text>
<svg:text dy=".35em" text-anchor="start">left-align, middle-baseline</svg:text>
<svg:text dy=".35em" text-anchor="middle">center-align, middle-baseline</svg:text>
<svg:text dy=".35em" text-anchor="end">right-align, middle-baseline</svg:text>
<svg:text dy=".71em" text-anchor="start">left-align, top-baseline</svg:text>
<svg:text dy=".71em" text-anchor="middle">center-align, top-baseline</svg:text>
<svg:text dy=".71em" text-anchor="end">right-align, top-baseline</svg:text>

It's possible that there is a better way to specify the text baseline using SVG's baseline alignment properties, but these don't seem to be widely supported by browsers. Lastly, the font color is typically specified using the fill style (you can also use stroke), and the font is controlled using the font, font-family, font-size and related styles. Some browsers also support CSS3 properties, such as text-shadow.

# svg:path d="" transform=""

The path element represents the outline of a shape which can be filled, stroked, used as a clipping path, or any combination of the three. The d attribute defines the path data, which is a mini-language of path commands, such as moveto (M), lineto (L) and closepath (Z). The path element is a generalization of all other shapes in SVG, and can be used to draw nearly anything!

Path Data Generators

To simplify the construction of the d attribute for path elements, D3 includes a number of helper classes for generating path data. If you're familiar with Protovis, you'll find that these path generators are similar to Protovis mark types: each generator is a function of data. So, if your data is a sequence of xy coordinates, you can define accessor functions that the path generators use to produce path data. For example, you might define a line generator:

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

Then later on, you can use this function to set the d attribute:

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

Whatever data is bound to g (in this example) will be passed to the line instance. Thus, the data must be specified as an array. For every element in the data array, the x- and y-accessor functions are used to pull out the control point coordinates.

A path generator, such as that returned by d3.svg.line, is both an object and a function. That is: you can call the generator like any other function, and the generator has additional methods that change its behavior. Like other classes in D3, path generators follow the method chaining pattern where setter methods return the generator itself, allowing multiple setters to be invoked in a concise statement.

# d3.svg.line()

x, y 접근자 함수와 선형 interpolation을 기본으로 가진 라인 제네레이터를 생성한다. (원소가 두개인 숫자 배열을 입력 데이터로 취한다. 자세한건 아래를 보자.) 반환된 함수는 꺽은선 곡선(piecewise linear curve)이나 폴리라인(polyline)을 위한 패스 데이터를 생성한다. 다음과 같은 라인 차트처럼.

line

interpolation를 변경함으로 spline과 step 함수를 생성할 수도 있다. 또한, line() 명령 뒤에 패스 명령어를 추가할 수 있다. 예를 들어. 닫힌 패스를 생성하기를 원하면 닫힌 패스 명령어(Z)를 추가한다.

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

line 제네레이터는 area 제네레이터와 결합해서 동작하도록 설계되었다. 예를 들어, area 차트를 제작할 때, fill 스타일이 있는 area 제네레이터와 영역의 윗선을 강조하기 위한 stroke 스타일을 준 line 제네레이터를 함께 사용한다. line 제네레이터는 d 속성을 지정하기 위해서만 사용되므로 fill, stroke, stroke-width같은 SVG 표준 스타일과 속성을 사용하는 라인의 외형을 조절할 수 있다.

# line(data[, index])

지정한 data 배열원 원로로 패스 데이터 문자열을 반환한다. 옵션인 index는 line의 접근자 함수를 통해서 전달되어 지정된다.

# line.x([x])

x 인자를 넘기면 넘긴 함수나 상수가 x-접근자가 된다. 인자를 넘기지 않으면 현재 x-접금자를 반환한다. 이 접근자는 라인 제네레이터로 전달된 데이터 배열안에 각 원소에 대해서 호출된다. 기본 접근자는 입력 원소가 숫자 원소 두개의 배열로 가정한다.

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

하지만 일반적으로 x-접근자는 기본 접근자를 쓰지 않고 개발자가 지정한다. 왜냐하면 입력 데이터가 출력과 형태가 다르거나, scale를 적용하길 원하기 때문이다. 예를 들어 데이터가 튜플(tuple)이 아닌 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 컨텍스트는 선택물에서 현재 요소이다. (일반적으로 그 line 함수를 호출하는 this컨텍스트와 같지만 일반적인 경우 line 제네레이터는 attr 오퍼레이터로 전달된다. 그래서 this 컨텍스트는 연관된 DOM 요소가 된다. ) 함수는 전달인자가 두 개다. 현재 dataum(d)와 현재 index(i)다. 이 컨텍스트(x-접근자 함수 내부)에서는 index가 선택물의 현재 요소 인덱스가 아니라 라인의 제어 지점의 배열 인덱스다. x-접근자는 data 배열에 지정된 순서대로 datum당 정확히 한번씩 호출된다. 그러므로 난수 생성자 같은 비결정적 접근자를 지정하는게 가능하다. 또한 함수가 아닌 상수로 x-접근자를 지정하는 것도 가능하다. 그러면 모든 지점이 같은 x 좌표를 갖게 된다.

# line.y([y])

y 전달인자를 넘기면, 그 함수나 상수로 y-접근자를 지정한다. 인자를 넘기지 않으면 현제 y-접근자를 반환한다. 이 접근자는 line 제네레이터로 전달된 데이터 배열안의 개별 요소별로 호출된다. 기본 접근자는 입력 원소가 숫자 원소 두개의 배열로 가정한다.

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

y 전달인자를 지정하는 예제는 x 접근자와 유사해 보인다. 다른점은 다른 그래픽 라이브러리 처럼 SVG는 시작 지점으로 상단 좌측 모서리를 사용한다는 점이다. 그래서 y 값이 높으면 화면상에 아래쪽에 위치한다. 시각화(차트)를 위해서는 하단 좌측 모서리를 시작점으로 할 필요가 있다. 이를 위한 가장 쉬운 방법은 range([0, h])대신에 range([h, 0])을 사용해서 y-스케일의 범위를 역치 시키는 것이다.

# line.interpolate([interpolate])

If interpolate is specified, sets the interpolation mode to the specified string. If interpolate is not specified, returns the current interpolation mode. The following modes are supported:

  • linear - piecewise linear segments, as in a polyline.
  • step-before - alternate between vertical and horizontal segments, as in a step function.
  • step-after - alternate between horizontal and vertical segments, as in a step function.
  • basis - a B-spline, with control point duplication on the ends.
  • basis-open - an open B-spline; may not intersect the start or end.
  • basis-closed - a closed B-spline, as in a loop.
  • bundle - equivalent to basis, except the tension parameter is used to straighten the spline.
  • cardinal - a Cardinal spline, with control point duplication on the ends.
  • cardinal-open - an open Cardinal spline; may not intersect the start or end, but will intersect other control points.
  • cardinal-closed - a closed Cardinal spline, as in a loop.
  • monotone - cubic interpolation that preserves monotonicity in y.

The behavior of some of these interpolation modes may be further customized by specifying a tension.

# line.tension([tension])

If tension is specified, sets the Cardinal spline interpolation tension to the specified number in the range [0, 1]. If tension is not specified, returns the current tension. The tension only affects the Cardinal interpolation modes: cardinal, cardinal-open and cardinal-closed. The default tension is 0.7. In some sense, this can be interpreted as the length of the tangent; 1 will yield all zero tangents, and 0 yields a Catmull-Rom spline.

Note that the tension must be specified as a constant, rather than a function, as it is constant for the entirety of the line. However, it is still possible to generate multiple lines with different tensions using the same generator. For example:

svg.selectAll("path")
    .data([0, 0.2, 0.4, 0.6, 0.8, 1])
  .enter().append("svg:path")
    .attr("d", function(d) { return line.tension(d)(data); });

In this example (see the live version), the tension is set before each invocation of the line generator, thus resulting in lines with the same data but different paths.

# line.defined([defined])

Gets or sets or sets the accessor function that controls where the line is defined. If defined is specified, sets the new accessor function and returns the line. If defined is not specified, returns the current accessor which defaults to function() { return true; }. The defined accessor can be used to define where the line is defined and undefined, which is typically useful in conjunction with missing data; the generated path data will automatically be broken into multiple distinct subpaths, skipping undefined data. For example, if you want to ignore y-values that are not a number (or undefined), you can say:

line.defined(function(d) { return !isNaN(d[1]); });

# d3.svg.line.radial()

Constructs a new radial line generator with the default radius- and angle-accessor functions (that assume the input data is a two-element array of numbers; see below for details), and linear interpolation. The returned function generates path data for an open piecewise linear curve, or polyline, as with the Cartesian line generator.

# line(data[, index])

Returns the path data string for the specified array of data elements. An optional index may be specified, which is passed through to the line's accessor functions.

# line.radius([radius])

If radius is specified, sets the radius-accessor to the specified function or constant. If radius is not specified, returns the current radius-accessor. This accessor is invoked for each element in the data array passed to the line generator. The default accessor assumes that each input element is a two-element array of numbers:

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

This method is a transformation of the Cartesian line.x method.

# line.angle([angle])

If angle is specified, sets the angle-accessor to the specified function or constant in radians. If angle is not specified, returns the current angle-accessor. This accessor is invoked for each element in the data array passed to the line generator. The default accessor assumes that each input element is a two-element array of numbers:

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

This method is a transformation of the Cartesian line.y method.

# d3.svg.area()

기본값으로 x-, y0-, y1-접근자 함수(원소가 두개인 숫자 배열을 입력 데이터로 취한다. 자세한건 아래를 보자.)와 linear interpolation를 가진 area 제네레이터를 새로 생성한다. 반환된 함수는 꺾은선 곡선(piecewise linear curve)이나 폴리라인(polyline)을 위한 패스 데이터를 생성한다. 다음과 같은 영역 차트처럼.

area

이론적으로 폴리곤은 두개의 lines를 사용해 형성한다. 탑라인은 x-과 y1접근자 함수를 사용해서 형성되고 왼쪽에서 오른쪽으로 진행된다. 그리고 바닥 라인이 이 라인에 추가되는데 x-과 y0-접근자를 사용하고 오른쪽에서 왼쪽으로 진행한다. 90˚로 패스 요소를 회전하기 위해 transform 속성을 지정해서 수직 영역를 생성할 수도 있다. interpolation을 변경해서 spline과 step함수를 생성할 수도 있다.

area 제네레이터는 line 제네레이터와 결합해서 동작하도록 설계되었다. 예를 들어. area 차트를 제작할 때, fill 스타일을 적용한 area 제네레이터와 영역의 윗선을 강조하기 위한 stroke 스타일 적용을 한 line 제네레이터를 함께 사용한다. area 제네레이터는 d 속성을 지정하기 위해서만 사용되므로, fill같은 SVG 표준 스타일과 속성을 사용하는 라인의 외형을 조절할 수 있다.

streamgraphs( 선으로 구분된 영역 차트 )를 만들기 위해서는 stack 레이아웃을 사용한다. 이 레이아웃은 한 스리즈의 각 값에 대해서 y0 속성을 지정한다. 그리고 그것은 y0-와 y1-접근자에서 사용될 수 있다. 주의할 점은 각 시리즈는 시리즈별 값이 동일 값이여야만 한다는 사실이다. 그리고 각 값은 동일 좌표여야 한다. 만약 데이터가 유실되거나 시리즈의 x좌표가 일치하지 않으면 레이아웃을 정하기전에 데이터를 다시 집계하고 보정해야 한다.

# area(data[, index])

지정한 data배열의 원소로 패스 데이터 문자열을 반환한다. 옵션인 index는 area의 접근자 함수를 통해서 전달되어 지정된다.

# area.x([x])

x 인자를 넘기면 넘긴 함수나 상수가 x-접근자가 된다. 인자를 넘기지 않으면 현재 x-접금자를 반환한다. 이 접근자는 area 제네레이터로 전달된 데이터 배열안에 각 원소에 대해서 호출된다. 기본 접근자는 입력 원소가 숫자 원소 두개의 배열로 가정한다.

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

하지만 일반적으로 x-접근자는 기본 접근자를 쓰지 않고 개발자가 지정한다. 왜냐하면 입력 데이터가 출력과 형태가 다르거나, scale를 적용하길 원하기 때문이다. 예를 들어 데이터가 튜플(tuple)이 아닌 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 컨텍스트는 선택물에서 현재 요소이다. (일반적으로 그 line 함수를 호출하는 this컨텍스트와 같지만 일반적인 경우 area 제네레이터는 attr 오퍼레이터로 전달된다. 그래서 this 컨텍스트는 연관된 DOM 요소가 된다. ) 함수는 전달인자가 두 개다. 현재 dataum(d)와 현재 index(i)다. 이 컨텍스트(x-접근자 함수 내부)에서는 index가 선택물의 현재 요소 인덱스가 아니라 라인의 제어 지점의 배열 인덱스다. x-접금자는 data 배열에 지정된 순서대로 datum당 정확히 한번씩 호출된다. 그러므로 난수 생성자 같은 비결정적 접근자를 지정하는게 가능하다. 또한 함수가 아닌 상수로 x-접근자를 지정하는 것도 가능하다. 그러면 모든 지점이 같은 x 좌표를 갖게 된다.

# area.x0([x0])

# area.x1([x1])

# area.y([y])

# area.y0([y0])

y0 인자를 넘기면 넘긴 함수나 상수가 y0-접근자가 된다. 인자를 넘기지 않으면 현재 y0-접근자를 반환한다. 이 접근자는 area 제네레이터로 전달된 데이터 배열안에 각 원소에 대해서 호출된다. 기본 접근자는 상수 0이고 그러면 y = 0 으로 고정된 기준선을 사용한다. y0-접근자를 지정하는 방법은 유사한 x 접근자 내용을 참고하라.

# area.y1([y1])

y1 인자를 넘기면 넘긴 함수나 상수가 y1-접근자가 된다. 인자를 넘기지 않으면 현재 y1-접근자를 반환한다. 이 접근자는 area 제네레이터로 전달된 데이터 배열안에 각 원소에 대해서 호출된다. 기본 접근자는 입력 원소를 숫자 원소 두개의 배열로 가정한다.

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

y1-접근자를 지정하는 방법은 유사한 x 접근자 내용을 참고하라. 다른 그래픽 라이브러리 처럼 SVG는 시작 지점으로 상단 좌측 모서리를 사용한다. 그래서 y값이 높으면 화면상에 아래쪽에 위치한다. 시각화(차트)를 위해서는 하단 좌측 모서리를 시작점으로 할 필요가 있다. 이를 위한 가장 쉬운 방법은 range([0, h])대신에 range([h, 0])을 사용해서 y-스케일의 범위를 역치 시키는 것이다.

# area.interpolate([interpolate])

If interpolate is specified, sets the interpolation mode to the specified string. If interpolate is not specified, returns the current interpolation mode. The following modes are supported:

  • linear - piecewise linear segments, as in a polyline.
  • step-before - alternate between vertical and horizontal segments, as in a step function.
  • step-after - alternate between horizontal and vertical segments, as in a step function.
  • basis - a B-spline, with control point duplication on the ends.
  • basis-open - an open B-spline; may not intersect the start or end.
  • cardinal - a Cardinal spline, with control point duplication on the ends.
  • cardinal-open - an open Cardinal spline; may not intersect the start or end, but will intersect other control points.
  • monotone - cubic interpolation that preserves monotonicity in y.

The behavior of some of these interpolation modes may be further customized by specifying a tension. Technically, the basis-closed and cardinal-closed interpolation modes are also supported, but these make more sense in the context of a line rather than an area.

# area.tension([tension])

If tension is specified, sets the Cardinal spline interpolation tension to the specified number in the range [0, 1]. If tension is not specified, returns the current tension. The tension only affects the Cardinal interpolation modes: cardinal, cardinal-open and cardinal-closed. The default tension is 0.7. In some sense, this can be interpreted as the length of the tangent; 1 will yield all zero tangents, and 0 yields a Catmull-Rom spline. Note that the tension must be specified as a constant, rather than a function, as it is constant for the entirety of the area.

# area.defined([defined])

Gets or sets or sets the accessor function that controls where the area is defined. If defined is specified, sets the new accessor function and returns the area. If defined is not specified, returns the current accessor which defaults to function() { return true; }. The defined accessor can be used to define where the area is defined and undefined, which is typically useful in conjunction with missing data; the generated path data will automatically be broken into multiple distinct subpaths, skipping undefined data. For example, if you want to ignore y-values that are not a number (or undefined), you can say:

area.defined(function(d) { return !isNaN(d[1]); });

# d3.svg.area.radial()

# area(data[, index])

Returns the path data string for the specified array of data elements. An optional index may be specified, which is passed through to the area's accessor functions.

# area.radius([radius])

# area.innerRadius([radius])

# area.innerRadius([radius])

# area.angle([angle])

# area.startAngle([angle])

# area.endAngle([angle])

# d3.svg.arc()

Constructs a new arc generator with the default innerRadius-, outerRadius-, startAngle- and endAngle-accessor functions (that assume the input data is an object with named attributes matching the accessors; see below for details). While the default accessors assume that the arc dimensions are all specified dynamically, it is very common to set one or more of the dimensions as a constant, such as setting the inner radius to zero for a pie chart. The returned function generates path data for a closed solid arc, as in a pie or donut chart:

arc

In fact, four forms are possible: a circle (when the inner radius is zero and the angular span is greater than or equal to 2π), a circular sector (when the inner radius is zero and the angular span is less than 2π), an [annulus](http://en.wikipedia.org/wiki/Annulus_(mathematics\)) (when the inner radius is non-zero and the angular span is greater than or equal to 2π), and an annular sector (when the inner radius is non-zero and the angular span is less than 2π).

# arc(datum[, index])

Returns the path data string for the specified datum. An optional index may be specified, which is passed through to the arc's accessor functions.

# arc.innerRadius([radius])

If radius is specified, sets the innerRadius-accessor to the specified function or constant. If radius is not specified, returns the current innerRadius-accessor. This accessor is invoked on the argument passed to the arc generator. The default accessor assumes that the input data is an object with suitably-named attributes:

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

Typically, a innerRadius-accessor is specified because the input data is in a different format, because you want to apply a scale, or because you want to specify a constant inner radius for a donut chart.

The innerRadius-accessor is invoked in the same manner as other value functions in D3. The this context of the function is the current element in the selection. (Technically, the same this context that invokes the arc function; however, in the common case that the arc generator is passed to the attr operator, the this context will be the associated DOM element.) The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the innerRadius-accessor as a constant rather than a function.

# arc.outerRadius([radius])

If radius is specified, sets the outerRadius-accessor to the specified function or constant. If radius is not specified, returns the current outerRadius-accessor. This accessor is invoked on the argument passed to the arc generator. The default accessor assumes that the input data is an object with suitably-named attributes:

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

Typically, a outerRadius-accessor is specified because the input data is in a different format, because you want to apply a scale, or because you want to specify a constant inner radius for a donut chart.

The outerRadius-accessor is invoked in the same manner as other value functions in D3. The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the outerRadius-accessor as a constant rather than a function.

# arc.startAngle([angle])

If angle is specified, sets the startAngle-accessor to the specified function or constant. If angle is not specified, returns the current startAngle-accessor. Angles are specified in radians, even though SVG typically uses degrees. This accessor is invoked on the argument passed to the arc generator. The default accessor assumes that the input data is an object with suitably-named attributes:

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

For constructing pie or donut charts, you will need to compute the start angle of each arc as the end angle of the previous arc. This can be done very conveniently using the pie layout, which is similar to the stack layout; given a set of input data, the pie layout will construct arc objects with startAngle and endAngle attributes that you can use with the default arc accessors.

The startAngle-accessor is invoked in the same manner as other value functions in D3. The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the startAngle-accessor as a constant rather than a function.

# arc.endAngle([angle])

If angle is specified, sets the endAngle-accessor to the specified function or constant. If angle is not specified, returns the current startAngle-accessor. Angles are specified in radians, even though SVG typically uses degrees. This accessor is invoked on the argument passed to the arc generator. The default accessor assumes that the input data is an object with suitably-named attributes:

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

For constructing pie or donut charts, you will need to compute the end angle of each arc as offset from the start angle. This can be done very conveniently using the pie layout, which is similar to the stack layout; given a set of input data, the pie layout will construct arc objects with startAngle and endAngle attributes that you can use with the default arc accessors.

The endAngle-accessor is invoked in the same manner as other value functions in D3. The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the endAngle-accessor as a constant rather than a function.

# arc.centroid(arguments…)

Computes the centroid of the arc that would be generated from the specified input arguments; typically, the arguments are the current datum (d), and optionally the current index (i). The centroid is defined as the midpoint in polar coordinates of the inner and outer radius, and the start and end angle. This provides a convenient location for arc labels. For example:

arcs.append("svg:text")
    .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .text(function(d) { return d.value; });

Alternatively, you can use SVG's transform attribute to rotate text into position, though you may need to convert radians back into degrees. Yet another possibility is to use a textPath element to curve the label along the path of the arc!

# d3.svg.symbol()

Constructs a new symbol generator with the default type- and size-accessor functions (that make no assumptions about input data, and produce a circle sized 64 square pixels; see below for details). While the default accessors generate static symbols, it is common to set one or more of the accessors using a function, such as setting the size proportional to a dimension of data for a scatterplot. The returned function generates path data for various symbols, as in a dot plot:

symbol

Note that the symbol does not include accessors for x and y. Instead, you can use the path element's transform attribute to position the symbols, as in:

vis.selectAll("path")
    .data(data)
  .enter().append("svg:path")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; })
    .attr("d", d3.svg.symbol());

In the future, we may add x- and y-accessors for parity with the line and area generators. The symbol will be centered at the origin (0,0) of the local coordinate system. You can also use SVG's built-in basic shapes to produce many of these symbol types, though D3's symbol generator is useful in conjunction with path elements because you can easily change the symbol type and size as a function of data.

# symbol(datum[, index])

Returns the path data string for the specified datum. An optional index may be specified, which is passed through to the symbol's accessor functions.

# symbol.type([type])

If type is specified, sets the type-accessor to the specified function or constant. If type is not specified, returns the current type-accessor. The default accessor is the constant "circle", and the following types are supported:

Types are normalized to have the same area in square pixels, according to the specified size. However, note that different types' sizes may be affected by the stroke and stroke width in different ways. All of the types are designed to be visible when only a fill style is used (unlike the Protovis cross), although they generally look better when both a fill and stroke is used.

The type-accessor is invoked in the same manner as other value functions in D3. The this context of the function is the current element in the selection. (Technically, the same this context that invokes the arc function; however, in the common case that the symbol generator is passed to the attr operator, the this context will be the associated DOM element.) The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the type-accessor as a constant rather than a function.

# symbol.size([size])

If size is specified, sets the size-accessor to the specified function or constant in square pixels. If size is not specified, returns the current size-accessor. The default is 64. This accessor is invoked on the argument passed to the symbol generator. Typically, a size-accessor is specified as a function when you want the size of the symbol to encode a quantitative dimension of data, or a constant it you simply want to make all the dots bigger or smaller. If you want to specify a radius rather than the size, you must do so indirectly, for example using a pow scale with exponent 2.

# d3.svg.chord()

Constructs a new chord generator with the default accessor functions (that assume the input data is an object with named attributes matching the accessors; see below for details). While the default accessors assume that the chord dimensions are all specified dynamically, it is very common to set one or more of the dimensions as a constant, such as the radius. The returned function generates path data for a closed shape connecting two [arcs](http://en.wikipedia.org/wiki/Arc_(geometry\)) with quadratic Bézier curves, as in a chord diagram:

chord

A chord generator is often used in conjunction with an arc generator, so as to draw annular segments at the start and end of the chords. In addition, the chord layout is useful for generating objects that describe a set of grouped chords from a matrix, compatible with the default accessors.

# chord(datum[, index])

Returns the path data string for the specified datum. An optional index may be specified, which is passed through to the chord's accessor functions.

# chord.source([source])

If source is specified, sets the source-accessor to the specified function or constant. If source is not specified, returns the current source-accessor. The purpose of the source accessor is to return an object that describes the starting arc of the chord. The returned object is subsequently passed to the radius, startAngle and endAngle accessors. This allows these other accessors to be reused for both the source and target arc descriptions. The default accessor assumes that the input data is an object with suitably-named attributes:

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

The source-accessor is invoked in the same manner as other value functions in D3. The this context of the function is the current element in the selection. (Technically, the same this context that invokes the arc function; however, in the common case that the symbol generator is passed to the attr operator, the this context will be the associated DOM element.) The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the source-accessor as a constant rather than a function.

# chord.target([target])

If target is specified, sets the target-accessor to the specified function or constant. If target is not specified, returns the current target-accessor. The purpose of the target accessor is to return an object that describes the ending arc of the chord. The returned object is subsequently passed to the radius, startAngle and endAngle accessors. This allows these other accessors to be reused for both the source and target arc descriptions. The default accessor assumes that the input data is an object with suitably-named attributes:

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

The target-accessor is invoked in the same manner as other value functions in D3. The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the target-accessor as a constant rather than a function.

# chord.radius([radius])

If radius is specified, sets the radius-accessor to the specified function or constant. If radius is not specified, returns the current radius-accessor. The default accessor assumes that the input source or target description is an object with suitably-named attributes:

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

The radius-accessor is invoked in a similar manner as other value functions in D3. The function is passed two arguments, the current source description (derived from the current datum, d) and the current index (i). It is also possible to specify the radius-accessor as a constant rather than a function.

# chord.startAngle([angle])

If startAngle is specified, sets the startAngle-accessor to the specified function or constant. If startAngle is not specified, returns the current startAngle-accessor. Angles are specified in radians, even though SVG typically uses degrees. The default accessor assumes that the input source or target description is an object with suitably-named attributes:

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

The startAngle-accessor is invoked in a similar manner as other value functions in D3. The function is passed two arguments, the current source or target description (derived from the current datum, d) and the current index (i). It is also possible to specify the startAngle-accessor as a constant rather than a function.

# chord.endAngle([angle])

If endAngle is specified, sets the endAngle-accessor to the specified function or constant. If endAngle is not specified, returns the current endAngle-accessor. Angles are specified in radians, even though SVG typically uses degrees. The default accessor assumes that the input source or target description is an object with suitably-named attributes:

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

The endAngle-accessor is invoked in a similar manner as other value functions in D3. The function is passed two arguments, the current source or target description (derived from the current datum, d) and the current index (i). It is also possible to specify the endAngle-accessor as a constant rather than a function.

# d3.svg.diagonal()

Constructs a new diagonal generator with the default accessor functions (that assume the input data is an object with named attributes matching the accessors; see below for details). The returned function generates the path data for a cubic Bézier connecting the source and target points; the tangents are specified to produce smooth fan-in and fan-out when connecting nodes, as in a node-link diagram:

diagonal

Although diagonals default to Cartesian (axis-aligned) orientations, they can be used in radial and other orientations using a projection.

# diagonal(datum[, index])

Returns the path data string for the specified datum. An optional index may be specified, which is passed through to the diagonal's accessor functions.

# diagonal.source([source])

If source is specified, sets the source-accessor to the specified function or constant. If source is not specified, returns the current source-accessor. The purpose of the source accessor is to return an object that describes the starting point of the diagonal. The returned object is subsequently passed to the projection. The default accessor assumes that the input data is an object with suitably-named attributes:

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

The source-accessor is invoked in the same manner as other value functions in D3. The this context of the function is the current element in the selection. (Technically, the same this context that invokes the diagonal function; however, in the common case that the symbol generator is passed to the attr operator, the this context will be the associated DOM element.) The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the source-accessor as a constant rather than a function.

# diagonal.target([target])

If target is specified, sets the target-accessor to the specified function or constant. If target is not specified, returns the current target-accessor. The purpose of the target accessor is to return an object that describes the ending point of the diagonal. The returned object is subsequently passed to the projection. The default accessor assumes that the input data is an object with suitably-named attributes:

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

The target-accessor is invoked in the same manner as other value functions in D3. The function is passed two arguments, the current datum (d) and the current index (i). It is also possible to specify the source-accessor as a constant rather than a function.

# diagonal.projection([projection])

If projection is specified, sets the projection to the specified function. If projection is not specified, returns the current projection. The projection converts the starting or ending point returned by the source and target accessors, returning a two-element array of numbers. The default accessor assumes that the input point is an object with x and y attributes:

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

The default accessor is thus compatible with D3's various node layouts, including tree, partition and cluster. For example, to produce a radial diagonal, assuming that the y attribute defines the radius in pixels, and the x attribute defines the angle in degrees:

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

The projection is invoked in a similar manner as other value functions in D3. The function is passed two arguments, the current source or target point (derived from the current data, d) and the current index (i).

# d3.svg.diagonal.radial()

# diagonal(datum[, index])

Returns the path data string for the specified datum. An optional index may be specified, which is passed through to the diagonal's accessor functions.

Clone this wiki locally