Giter Club home page Giter Club logo

d3-scale's Introduction

d3-scale

Scales are a convenient abstraction for a fundamental task in visualization: mapping a dimension of abstract data to a visual representation. Although most often used for position-encoding quantitative data, such as mapping the height in meters of a sample population to the height in pixels of bars in a bar chart, scales can represent virtually any visual encoding, such as diverging colors, stroke widths, or symbol size. Scales can also be used with virtually any type of data, such as named categorical data or discrete data that needs sensible breaks.

For continuous quantitative data, you often want a linear scale. (For time series data, a time scale.) If the distribution calls for it, you may transform data using a power scale or log scale. To aid differentiation, consider a quantize scale, which rounds continuous data to a fixed set of discrete values; similarly, a quantile scale computes quantiles from a sample population, and a threshold scale allows you to specify arbitrary thresholds to specify discrete breaks in continuous data.

For ordinal or categorical data, use an ordinal scale. Ordinal scales can specify an explicit mapping from a discrete set of data values to a discrete set of visual attributes (such as colors), but they are also useful for position-encoding ordinal data, such as bars in a bar chart or dots in an categorical scatterplot. Several built-in categorical color scales are also provided; if you don’t like these palettes, try ColorBrewer.

Scales have no intrinsic visual representation; for that, consider an axis. However, scales typically provide a ticks method (such as linear.ticks) that can be used to render reference marks.

Want a longer introduction? See these recommended tutorials:

Installing

If you use NPM, npm install d3-scale. Otherwise, download the latest release.

API Reference

Linear Scales

Linear scales are the most common and a good default choice to map a continuous input domain to a continuous output range. With a linear scale, each range value y can be expressed as a linear function of the domain value x: y = mx + b. The domain is typically a dimension of data you want to visualize, such as the height in meters of people in a sample population. The range is typically a dimension of the desired output visualization, such as the height in pixels of bars in a bar chart.

# linear()

Constructs a new linear scale with the default domain [0,1], the default range [0,1], the default interpolator and clamping disabled.

# linear(x)

Given a value x in the domain, returns the corresponding value y in the range. For example, a color encoding:

var s = linear().domain([10, 100]).range(["brown", "steelblue"]);
s(20); // "#9a3439"
s(50); // "#7b5167"

Or a position encoding:

var s = linear().domain([10, 100]).range([0, 960]);
s(20); // 106.66666666666666
s(50); // 426.66666666666663

# linear.invert(y)

Given a value y in the range, returns the corresponding value x in the domain: the inverse of linear. For example, a position encoding:

var s = linear().domain([10, 100]).range([0, 960]);
s.invert(106.66666666666667); // 20
s.invert(426.66666666666667); // 50

This method is only supported if the range is numeric, and may return undefined if the range is non-numeric (such as colors). For a valid value y in the range, linear(linear.invert(y)) equals y; similarly, for a valid value x in the domain, linear.invert(linear(x)) equals x. The invert method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

# linear.domain([domain])

If domain is specified, sets the scale’s domain to the specified array of numbers. The array must contain two or more numbers. If the elements in the given array are not numbers, they will be coerced to numbers. (A linear scale may thus be used to encode dates; however, a time scale is recommended for calendar-based ticks.) If domain is not specified, returns the scale’s current domain.

Although linear scales typically have two values each in their domain and range, specifying more than two values produces a “polylinear” scale. A polylinear scale represents multiple piecewise linear scales that divide a continuous domain and range. For example, to create a diverging color scale that interpolates between white and red for negative values, and white and green for positive values, say:

var s = linear().domain([-1, 0, 1]).range(["red", "white", "green"]);
s(-0.5); // "#ff8080"
s(+0.5); // "#80c080"

Internally, a polylinear scale performs a binary search for the range interpolator corresponding to the given domain value. Thus, the domain must be in ascending or descending order. If the domain and range have different lengths N and M, only the first min(N,M) elements in each are observed.

# linear.range([range])

If range is specified, sets the scale’s range to the specified array of values. The array must contain two or more values. Unlike the domain, elements in the given array need not be numbers; any value that is supported by the underlying interpolator will work; however, numeric ranges are required for invert. If range is not specified, returns the scale’s current range.

# linear.rangeRound(range)

Sets the scale’s range to the specified array of values while also setting the scale’s interpolator to interpolateRound. This is a convenience method equivalent to:

s.range(range).interpolate(interpolateRound);

The rounding interpolator is sometimes useful for avoiding antialiasing artifacts, though also consider shape-rendering: crispEdges. Note that this interpolator can only be used with numeric ranges.

# linear.interpolate([interpolate])

If interpolate is specified, sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; these interpolators then map a normalized domain parameter t in [0,1] to the corresponding value in the range. If factory is not specified, returns the scale’s interpolator factory.

For example, if you create a diverging color scale with three colors in the range, two interpolators are created internally by the scale, equivalent to:

var s = scale.linear().domain([-100, 0, +100]).range(["red", "white", "green"]),
    i0 = interpolate("red", "white"),
    i1 = interpolate("white", "green");

Perhaps the most common reason to specify a custom interpolator is to change the color space of interpolation. For example, to use the HCL color space:

var s = scale.linear()
    .domain([10, 100])
    .range(["brown", "steelblue"])
    .interpolate(interpolateHcl);

See d3-color for more color interpolators.

Note: the default interpolator may reuse return values. For example, if the domain values are arbitrary objects, then the default interpolator always returns the same object, modifying it in-place. If the scale is used to set an attribute or style, you typically don’t have to worry about this recyling of the scale’s return value; however, if you need to store the scale’s return value, specify your own interpolator or make a copy as appropriate.

# linear.clamp([clamp])

If clamp is specified, enables or disables clamping accordingly. If clamping is disabled and the scale is passed a value outside the domain, the scale may return a value outside the range through linear extrapolation. If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to linear.invert. For example:

var s = linear().domain([10, 100]).range([0, 960]);
s(-10); // -213.33333333333331
s.invert(-213.33333333333331); // -10
s.clamp(true);
s(-10); // 0
s.invert(-213.33333333333331); // 10

If clamp is not specified, returns whether or not the scale currently clamps values to within the range.

# linear.nice([count])

Extends the domain so that it starts and ends on nice round values. This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. An optional tick count argument allows greater control over the step size used to extend the bounds, guaranteeing that the returned ticks will exactly cover the domain.

Nicing is useful if the domain is computed from data, say using extent, and may be irregular. For example, for a domain of [0.20147987687960267, 0.996679553296417], a nice domain might be [0.2, 1.0]. If the domain has more than two values, nicing the domain only affects the first and last value.

# linear.ticks([count])

Returns approximately count representative values from the scale’s domain. If count is not specified, it defaults to 10. The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. The specified count is only a hint; the scale may return more or fewer values depending on the domain.

# linear.tickFormat(count[, specifier])

Returns a number format function suitable for displaying a tick value. The specified count should have the same value as the count that is used to generate the tick values. You don’t have to use the scale’s built-in tick format, but it automatically computes the appropriate precision based on the fixed interval between tick values.

The optional specifier argument allows a custom format where the precision of the format is automatically substituted by the scale to be appropriate for the tick interval. For example, to format percentage change, you might say:

var s = linear().domain([-1, 1]),
    ticks = s.ticks(5),
    format = s.tickFormat(5, "+%");

ticks.map(format); // ["-100%", "-50%", "+0%", "+50%", "+100%"]

If specifier uses the format type s, the scale will return a SI-prefix format based on the largest value in the domain. If the specifier already specifies a precision, this method is equivalent to format.

# linear.copy()

Returns an exact copy of this linear scale. Changes to this scale will not affect the returned scale, and vice versa.

# cubehelix()

Constructs a new linear scale with the domain [0,1], a range of the default Cubehelix color scheme, and interpolateCubehelixLong as the interpolator.

# rainbow()

Constructs a new linear scale with the domain [0,0.5,1], a range of the less-angry rainbow color scheme (inspired by Matteo Niccoli’s perceptual rainbow), and interpolateCubehelixLong as the interpolator.

Power Scales

Power scales are similar to linear scales, except an exponential transform is applied to the input domain value before the output range value is computed. Each range value y can be expressed as a function of the domain value x: y = mx^k + b, where k is the exponent value. Power scales also support negative domain values, in which case the input value and the resulting output value are multiplied by -1.

# pow()

Constructs a new power scale with the default domain [0,1], the default range [0,1], the default exponent 1, the default interpolator and clamping disabled. (Note that this is effectively a linear scale until you set a different exponent.)

# pow(x)

Given a value x in the domain, returns the corresponding value y in the range. For example, a color encoding:

var s = pow().exponent(.5).domain([10, 100]).range(["brown", "steelblue"]);
s(20); // "#933b44"
s(50); // "#6f5c79"

Or a position encoding:

var s = pow().exponent(.5).domain([10, 100]).range([0, 960]);
s(20); // 183.90099810179152
s(50); // 548.7848671143346

# pow.invert(y)

Given a value y in the range, returns the corresponding value x in the domain: the inverse of pow. For example, a position encoding:

var s = pow().exponent(.5).domain([10, 100]).range([0, 960]);
s.invert(183.90099810179152); // 20
s.invert(548.7848671143346); // 50

This method is only supported if the range is numeric, and may return undefined if the range is non-numeric (such as colors). For a valid value y in the range, pow(pow.invert(y)) equals y; similarly, for a valid value x in the domain, pow.invert(pow(x)) equals x. The invert method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

# pow.exponent([k])

If k is specified, sets the current exponent to the given numeric value. If k is not specified, returns the current exponent. The default value is 1. (Note that this is effectively a linear scale until you set a different exponent.)

# pow.domain([domain])

If domain is specified, sets the scale’s domain to the specified array of numbers. The array must contain two or more numbers. If the elements in the given array are not numbers, they will be coerced to numbers. If domain is not specified, returns the scale’s current domain.

As with linear.domain, this method can accept more than two values for the domain and range, thus resulting in a “polypower” scale.

# pow.range([range])

If range is specified, sets the scale’s range to the specified array of values. The array must contain two or more values, matching the cardinality of the domain; otherwise, the longer of the two is truncated to match the other. The elements in the given array need not be numbers; any value that is supported by the underlying interpolator will work; however, numeric ranges are required for invert. If range is not specified, returns the scale’s current range.

# pow.rangeRound(range)

Sets the scale’s range to the specified array of values while also setting the scale’s interpolator to interpolateRound. This is a convenience method equivalent to:

s.range(range).interpolate(interpolateRound);

The rounding interpolator is sometimes useful for avoiding antialiasing artifacts, though also consider shape-rendering: crispEdges. Note that this interpolator can only be used with numeric ranges.

# pow.interpolate([interpolate])

If interpolate is specified, sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; these interpolators then map a normalized domain parameter t in [0,1] to the corresponding value in the range. If factory is not specified, returns the scale’s interpolator factory. See linear.interpolate for examples.

Note: the default interpolator may reuse return values. For example, if the domain values are arbitrary objects, then the default interpolator always returns the same object, modifying it in-place. If the scale is used to set an attribute or style, you typically don’t have to worry about this recyling of the scale’s return value; however, if you need to store the scale’s return value, specify your own interpolator or make a copy as appropriate.

# pow.clamp([clamp])

If clamp is specified, enables or disables clamping accordingly. If clamping is disabled and the scale is passed a value outside the domain, the scale may return a value outside the range through extrapolation. If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to pow.invert. See linear.clamp for examples. If clamp is not specified, returns whether or not the scale currently clamps values to within the range.

# pow.nice([count])

Extends the domain so that it starts and ends on nice round values. This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. An optional tick count argument allows greater control over the step size used to extend the bounds, guaranteeing that the returned ticks will exactly cover the domain.

Nicing is useful if the domain is computed from data, say using extent, and may be irregular. For example, for a domain of [0.20147987687960267, 0.996679553296417], the nice domain is [0.2, 1]. If the domain has more than two values, nicing the domain only affects the first and last value.

# pow.ticks([count])

Returns approximately count representative values from the scale’s domain. If count is not specified, it defaults to 10. The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. The specified count is only a hint; the scale may return more or fewer values depending on the domain.

# pow.tickFormat([count[, specifier]])

Returns a number format function suitable for displaying a tick value. The specified count should have the same value as the count that is used to generate the tick values. You don’t have to use the scale’s built-in tick format, but it automatically computes the appropriate precision based on the fixed interval between tick values. See linear.tickFormat for examples.

The optional specifier argument allows a custom format to be specified. If the format specifier doesn’t have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. This provides a convenient, declarative way of specifying a format whose precision will be automatically set by the scale.

# pow.copy()

Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

# sqrt()

Constructs a new power scale with the default domain [0,1], the default range [0,1], and the exponent 0.5. This is a convenience method equivalent to:

pow().exponent(0.5)

The returned scale is a function that takes a single argument x representing a value in the domain; the return value is the corresponding value in the range. Thus, the returned scale is equivalent to the sqrt function for numbers; for example sqrt(0.25) returns 0.5.

Log Scales

Log scales are similar to linear scales, except a logarithmic transform is applied to the input domain value before the output range value is computed. The mapping to the range value y can be expressed as a function of the domain value x: y = m log(x) + b.

As log(0) = -∞, a log scale domain must be strictly-positive or strictly-negative; the domain must not include or cross zero. A log scale with a positive domain has a well-defined behavior for positive values, and a log scale with a negative domain has a well-defined behavior for negative values. (For a negative domain, input and output values are implicitly multiplied by -1.) The behavior of the scale is undefined if you pass a negative value to a log scale with a positive domain or vice versa.

# log()

Constructs a new log scale with the default domain [1,10], the default range [0,1], and the base 10.

# log(x)

Given a value x in the domain, returns the corresponding value in the range. For example, a color encoding:

var s = log().domain([10, 100]).range(["brown", "steelblue"]);
s(20); // "#884454"
s(50); // "#63688a"

Or a position encoding:

var s = log().domain([10, 100]).range([0, 960]);
s(20); // 288.9887958374218
s(50); // 671.0112041625778

# log.invert(y)

Given a value y in the range, returns the corresponding value x in the domain; the inverse of log. For example:

var s = log().domain([10, 100]).range([0, 960]);
s.invert(288.9887958374218); // 20
s.invert(671.0112041625778); // 50

This method is only supported if the range is numeric, and may return undefined if the range is non-numeric (such as colors). For a valid value y in the range, log(log.invert(y)) equals y; similarly, for a valid value x in the domain, log.invert(log(x)) equals x. The invert method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

# log.base([base])

If base is specified, sets the base for this logarithmic scale. If base is not specified, returns the current base, which defaults to 10.

# log.domain([domain])

If domain is specified, sets the scale’s domain to the specified array of numbers. The array must contain two or more numbers. If the elements in the given array are not numbers, they will be coerced to numbers. If domain is not specified, returns the scale’s current domain.

As with linear.domain, this method can accept more than two values for the domain and range, thus resulting in a “polylog” scale.

# log.range([range])

If range is specified, sets the scale’s range to the specified array of values. The array must contain two or more values, matching the cardinality of the domain; otherwise, the longer of the two is truncated to match the other. The elements in the given array need not be numbers; any value that is supported by the underlying interpolator will work; however, numeric ranges are required for invert. If range is not specified, returns the scale’s current range.

# log.rangeRound(range)

Sets the scale’s range to the specified array of values while also setting the scale’s interpolator to interpolateRound. This is a convenience method equivalent to:

s.range(range).interpolate(interpolateRound);

The rounding interpolator is sometimes useful for avoiding antialiasing artifacts, though also consider shape-rendering: crispEdges. Note that this interpolator can only be used with numeric ranges.

# log.interpolate([interpolate])

If interpolate is specified, sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; these interpolators then map a normalized domain parameter t in [0,1] to the corresponding value in the range. If factory is not specified, returns the scale’s interpolator factory. See linear.interpolate for examples.

Note: the default interpolator may reuse return values. For example, if the domain values are arbitrary objects, then the default interpolator always returns the same object, modifying it in-place. If the scale is used to set an attribute or style, you typically don’t have to worry about this recyling of the scale’s return value; however, if you need to store the scale’s return value, specify your own interpolator or make a copy as appropriate.

# log.clamp([clamp])

If clamp is specified, enables or disables clamping accordingly. If clamping is disabled and the scale is passed a value outside the domain, the scale may return a value outside the range through extrapolation. If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to log.invert. See linear.clamp for examples. If clamp is not specified, returns whether or not the scale currently clamps values to within the range.

# log.nice()

Extends the domain so that it starts and ends on nice round values. This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value. The nearest round value is based on integer powers of the scale’s base.

Nicing is useful if the domain is computed from data, say using extent, and may be irregular. For example, for a domain of [0.20147987687960267, 0.996679553296417], the nice domain is [0.1, 1]. If the domain has more than two values, nicing the domain only affects the first and last value.

# log.ticks()

Returns representative values from the scale’s domain. The returned tick values are uniformly spaced within each power of ten, and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. Note that the number of ticks cannot be customized (due to the nature of log scales); however, you can filter the returned array of values if you want to reduce the number of ticks.

# log.tickFormat([count[, format]])

Returns a number format function suitable for displaying a tick value. If a count is specified, then some of the tick labels may not be displayed; this is useful if there is not enough room to fit all of the tick labels. However, note that the tick marks will still be displayed (so that the log scale distortion remains visible).

When specifying a count, you may also override the format function; you can also specify a format specifier as a string, and it will automatically be converted to a function with format. For example, to get a tick formatter that will display 20 ticks of a currency:

s.tickFormat(20, "$,f")

If the format specifier doesn’t have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. This provides a convenient, declarative way of specifying a format whose precision will be automatically set by the scale.

# log.copy()

Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

Time Scales

Time scales are a variant of linear scales that have a time domain: domain values are coerced to dates rather than numbers, and time.invert likewise returns a date. More importantly, time scales implement ticks based on conventional time intervals, taking the pain out of generating axes for temporal domains.

# time()

Constructs a new time scale with the default domain [2000-01-01,2000-01-02], the default range [0,1], the default interpolator and clamping disabled.

# time(date)

Given a date in the domain, returns the corresponding value in the range. For example, a position encoding:

var s = time()
    .domain([new Date(2000, 0, 1), new Date(2000, 0, 2)])
    .range([0, 960]);

s(new Date(2000, 0, 1,  5)); // 200
s(new Date(2000, 0, 1, 16)); // 640

# time.invert(y)

Given a value y in the range, returns the corresponding date in the domain: the inverse of time. For example, a position encoding:

var s = time()
    .domain([new Date(2000, 0, 1), new Date(2000, 0, 2)])
    .range([0, 960]);

s.invert(200); // Sat Jan 01 2000 05:00:00 GMT-0800 (PST)
s.invert(640); // Sat Jan 01 2000 16:00:00 GMT-0800 (PST)

This method is only supported if the range is numeric, and may return undefined if the range is non-numeric (such as colors). For a valid value y in the range, time(time.invert(y)) equals y; similarly, for a valid value x in the domain, time.invert(time(x)) equals x. The invert method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

# time.domain([dates])

If domain is specified, sets the scale’s domain to the specified array of dates. The array must contain two or more dates. If the elements in the given array are not dates, they will be coerced to dates. If domain is not specified, returns the scale’s current domain.

As with linear.domain, this method can accept more than two values for the domain and range, thus resulting in a “polylinear” scale.

# time.range([range])

If range is specified, sets the scale’s range to the specified array of values. The array must contain two or more values, matching the cardinality of the domain; otherwise, the longer of the two is truncated to match the other. The elements in the given array need not be numbers; any value that is supported by the underlying interpolator will work; however, numeric ranges are required for invert. If range is not specified, returns the scale’s current range.

# time.rangeRound([range])

Sets the scale’s range to the specified array of values while also setting the scale’s interpolator to interpolateRound. This is a convenience method equivalent to:

s.range(range).interpolate(interpolateRound);

The rounding interpolator is sometimes useful for avoiding antialiasing artifacts, though also consider shape-rendering: crispEdges. Note that this interpolator can only be used with numeric ranges.

# time.interpolate([interpolate])

If interpolate is specified, sets the scale’s range interpolator factory. This interpolator factory is used to create interpolators for each adjacent pair of values from the range; these interpolators then map a normalized domain parameter t in [0,1] to the corresponding value in the range. If factory is not specified, returns the scale’s interpolator factory. See linear.interpolate for examples.

Note: the default interpolator may reuse return values. For example, if the domain values are arbitrary objects, then the default interpolator always returns the same object, modifying it in-place. If the scale is used to set an attribute or style, you typically don’t have to worry about this recyling of the scale’s return value; however, if you need to store the scale’s return value, specify your own interpolator or make a copy as appropriate.

# time.clamp([clamp])

If clamp is specified, enables or disables clamping accordingly. If clamping is disabled and the scale is passed a value outside the domain, the scale may return a value outside the range through extrapolation. If clamping is enabled, the return value of the scale is always within the scale’s range. Clamping similarly applies to time.invert. See linear.clamp for examples. If clamp is not specified, returns whether or not the scale currently clamps values to within the range.

# time.nice([count])
# time.nice([intervalName[, step]])
# time.nice([interval])

Extends the domain so that it starts and ends on nice round values. This method typically modifies the scale’s domain, and may only extend the bounds to the nearest round value.

An optional tick count argument allows greater control over the step size used to extend the bounds, guaranteeing that the returned ticks will exactly cover the domain. Alternatively, a time interval or intervalName may be specified to explicitly set the ticks. If an intervalName is specified, an optional step may also be specified to skip some ticks. For example, nice("seconds", 10) will extend the domain to an even ten seconds (0, 10, 20, etc.). See time.ticks for further detail.

Nicing is useful if the domain is computed from data, say using extent, and may be irregular. For example, for a domain of [2009-07-13T00:02, 2009-07-13T23:48], the nice domain is [2009-07-13, 2009-07-14]. If the domain has more than two values, nicing the domain only affects the first and last value.

# time.ticks([count])
# time.ticks([intervalName[, step]])
# time.ticks([interval])

Returns representative dates from the scale’s domain. The returned tick values are uniformly-spaced (mostly), have sensible values (such every day at midnight), and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data.

An optional count may be specified to affect how many ticks are generated. If count is not specified, it defaults to 10. The specified count is only a hint; the scale may return more or fewer values depending on the domain. For example, to create ten default ticks, say:

var s = time();
s.ticks(10);
// [Sat Jan 01 2000 00:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 03:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 06:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 09:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 12:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 15:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 18:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 21:00:00 GMT-0800 (PST),
//  Sun Jan 02 2000 00:00:00 GMT-0800 (PST)]

The following time intervals are considered for automatic ticks:

  • 1-, 5-, 15- and 30-second.
  • 1-, 5-, 15- and 30-minute.
  • 1-, 3-, 6- and 12-hour.
  • 1- and 2-day.
  • 1-week.
  • 1- and 3-month.
  • 1-year.

In lieu of a count, a time interval or intervalName may be explicitly specified. The following interval names are supported:

  • milliseconds
  • seconds
  • minutes
  • hours
  • days
  • weeks
  • months
  • years

If an intervalName is specified, an optional step may also be specified to prune generated ticks. For example, ticks("minutes", 15) will generate ticks at 15-minute intervals:

var s = time().domain([new Date(2000, 0, 1, 0), new Date(2000, 0, 1, 2)]);
s.ticks("minutes", 15);
// [Sat Jan 01 2000 00:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 00:15:00 GMT-0800 (PST),
//  Sat Jan 01 2000 00:30:00 GMT-0800 (PST),
//  Sat Jan 01 2000 00:45:00 GMT-0800 (PST),
//  Sat Jan 01 2000 01:00:00 GMT-0800 (PST),
//  Sat Jan 01 2000 01:15:00 GMT-0800 (PST),
//  Sat Jan 01 2000 01:30:00 GMT-0800 (PST),
//  Sat Jan 01 2000 01:45:00 GMT-0800 (PST),
//  Sat Jan 01 2000 02:00:00 GMT-0800 (PST)]

This is equivalent to using minute.filter:

s.ticks(minute.filter(function(d) { return d.getMinutes() % 15 === 0; }));

Note: in some cases, such as with day ticks, specifying a step can result in irregular spacing of ticks because months have varying length.

# time.tickFormat([specifier])

Returns a time format function suitable for displaying tick values. If a format specifier is specified, this method is equivalent to format. If specifier is not specified, the default time format is returned. The default multi-scale time format chooses a human-readable representation based on the specified date as follows:

  • %Y - for year boundaries, such as 2011.
  • %B - for month boundaries, such as February.
  • %b %d - for week boundaries, such as Feb 06.
  • %a %d - for day boundaries, such as Mon 07.
  • %I %p - for hour boundaries, such as 01 AM.
  • %I:%M - for minute boundaries, such as 01:23.
  • :%S - for second boundaries, such as :45.
  • .%L - milliseconds for all other times, such as .012.

Although somewhat unusual, this default behavior has the benefit of providing both local and global context: for example, formatting a sequence of ticks as [11 PM, Mon 07, 01 AM] reveals information about hours, dates, and day simultaneously, rather than just the hours [11 PM, 12 AM, 01 AM]. See d3-time-format if you’d like to roll your own conditional time format.

# time.copy()

Returns an exact copy of this time scale. Changes to this scale will not affect the returned scale, and vice versa.

# utcTime()

Equivalent to time, but the returned time scale operates in Coordinated Universal Time rather than local time.

Quantize Scales

Quantize scales are a variant of linear scales with a discrete rather than continuous range. The input domain is still continuous, and divided into uniform segments based on the number of values in (the cardinality of) the output range. Each range value y can be expressed as a quantized linear function of the domain value x: y = m round(x) + b. See bl.ocks.org/4060606 for an example.

# quantize()

Constructs a new quantize scale with the default domain [0,1] and the default range [0,1]. Thus, the default quantize scale is equivalent to the Math.round function.

# quantize(x)

Given a value x in the input domain, returns the corresponding value y in the output range. For example, a color encoding:

var s = quantize().domain([0, 1]).range(["brown", "steelblue"]);
s(0.49); // "brown"
s(0.51); // "steelblue"

Dividing the domain into three equally-sized parts with different range values, say to compute an appropriate stroke width:

var s = quantize().domain([10, 100]).range([1, 2, 4]);
s(20); // 1
s(50); // 2
s(80); // 4

# quantize.invertExtent(y)

Returns the extent of values in the domain [x0, x1] for the corresponding value in the range y: the inverse of quantize. This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

var s = quantize().domain([10, 100]).range([1, 2, 4]);
s.invertExtent(2); // [40, 70]

# quantize.domain([domain])

If domain is specified, sets the scale’s domain to the specified two-element array of numbers. If the array contains more than two numbers, only the first and last number are used; if the elements in the given array are not numbers, they will be coerced to numbers. If domain is not specified, returns the scale’s current domain.

# quantize.range([range])

If range is specified, sets the scale’s range to the specified array of values. The array may contain any number of discrete values. The elements in the given array need not be numbers; any value or type will work. If range is not specified, returns the scale’s current range.

# quantize.copy()

Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

Quantile Scales

Quantile scales map an input domain to a discrete range. Although the domain is continuous and the scale will accept any reasonable input value, the domain is specified as a discrete set of values. The number of values in (the cardinality of) the output range determines the number of quantiles that will be computed from the domain. To compute the quantiles, the domain is sorted, and treated as a population of discrete values. The domain is typically a dimension of the data that you want to visualize, such as the daily change of the stock market. The range is typically a dimension of the desired output visualization, such as a diverging color scale. See bl.ocks.org/8ca036b3505121279daf for an example.

# quantile()

Constructs a new quantile scale with an empty domain and an empty range. The quantile scale is invalid until both a domain and range are specified.

# quantile(x)

Given a value x in the input domain, returns the corresponding value y in the output range.

# quantile.invertExtent(y)

Returns the extent of values in the domain [x0, x1] for the corresponding value in the range y: the inverse of quantile. This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

# quantile.domain([domain])

If domain is specified, sets the domain of the quantile scale to the specified set of discrete numeric values. The array must not be empty, and must contain at least one numeric value; NaN, null and undefined values are ignored and not considered part of the sample population. If the elements in the given array are not numbers, they will be coerced to numbers. A copy of the input array is sorted and stored internally. If domain is not specified, returns the scale’s current domain.

# quantile.range([range])

If range is specified, sets the discrete values in the range. The array must not be empty, and may contain any type of value. The number of values in (the cardinality, or length, of) the range array determines the number of quantiles that are computed. For example, to compute quartiles, range must be an array of four elements such as [0, 1, 2, 3]. If range is not specified, returns the current range.

# quantile.quantiles()

Returns the quantile thresholds. If the range contains n discrete values, the returned threshold array will contain n - 1 values. Values less than the first element in the thresholds array, quantiles()[0], are considered in the first quantile; greater values less than the second threshold are in the second quantile, and so on. Internally, the thresholds array is used with bisect to find the output quantile associated with the given input value.

# quantile.copy()

Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

Threshold Scales

Threshold scales are similar to quantize scales, except they allow you to map arbitrary subsets of the domain to discrete values in the range. The input domain is still continuous, and divided into slices based on a set of threshold values. The domain is typically a dimension of the data that you want to visualize, such as the height of students in meters in a sample population. The range is typically a dimension of the desired output visualization, such as a set of colors. See bl.ocks.org/3306362 for an example.

# threshold()

Constructs a new threshold scale with the default domain [.5] and the default range [0,1]. Thus, the default threshold scale is equivalent to the Math.round function for numbers; for example threshold(0.49) returns 0, and threshold(0.51) returns 1.

# threshold(x)

Given a value x in the input domain, returns the corresponding value y in the output range. For example:

var s = threshold().domain([0, 1]).range(["a", "b", "c"]);
s(-1);   // "a"
s(0);    // "b"
s(0.5);  // "b"
s(1);    // "c"
s(1000); // "c"

# threshold.invertExtent(y)

Returns the extent of values in the domain [x0, x1] for the corresponding value in the range y, representing the inverse mapping from range to domain. This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse. For example:

var s = threshold().domain([0, 1]).range(["a", "b", "c"]);
s.invertExtent("a"); // [undefined, 0]
s.invertExtent("b"); // [0, 1]
s.invertExtent("c"); // [1, undefined]

# threshold.domain([domain])

If domain is specified, sets the scale’s domain to the specified array of values. The values must be in sorted ascending order, or the behavior of the scale is undefined. The values are typically numbers, but any naturally ordered values (such as strings) will work; a threshold scale can be used to encode any type that is ordered. If the number of values in the scale’s range is N+1, the number of values in the scale’s domain must be N. If there are fewer than N elements in the domain, the additional values in the range are ignored. If there are more than N elements in the domain, the scale may return undefined for some inputs. If domain is not specified, returns the scale’s current domain.

# threshold.range([range])

If range is specified, sets the scale’s range to the specified array of values. If the number of values in the scale’s domain is N, the number of values in the scale’s range must be N+1. If there are fewer than N+1 elements in the range, the scale may return undefined for some inputs. If there are more than N+1 elements in the range, the additional values are ignored. The elements in the given array need not be numbers; any value or type will work. If range is not specified, returns the scale’s current range.

# threshold.copy()

Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

Identity Scales

Identity scales are a special case of linear scales where the domain and range are identical; the scale and its invert method are both the identity function. These scales are occasionally useful when working with pixel coordinates, say in conjunction with an axis or brush.

# identity()

Constructs a new identity scale with the default domain [0,1] and the default range [0,1]. An identity scale is always equivalent to the identity function.

# identity(x)
# identity.invert(x)

Returns the given value x.

# identity.domain([domain])
# identity.range([domain])

If domain is specified, sets the scale’s domain and range to the specified array of numbers. The array must contain two or more numbers. If the elements in the given array are not numbers, they will be coerced to numbers. If domain is not specified, returns the scale’s current domain (or equivalently, range).

# identity.ticks([count])

Returns approximately count representative values from the scale’s domain (or equivalently, range). If count is not specified, it defaults to 10. The returned tick values are uniformly spaced, have human-readable values (such as multiples of powers of 10), and are guaranteed to be within the extent of the domain. Ticks are often used to display reference lines, or tick marks, in conjunction with the visualized data. The specified count is only a hint; the scale may return more or fewer values depending on the domain.

# identity.tickFormat(count[, specifier])

Returns a number format function suitable for displaying a tick value. The specified count should have the same value as the count that is used to generate the tick values. You don’t have to use the scale’s built-in tick format, but it automatically computes the appropriate precision based on the fixed interval between tick values.

The optional specifier argument allows a custom format to be specified. If the format specifier doesn’t have a defined precision, the precision will be set automatically by the scale, returning the appropriate format. This provides a convenient, declarative way of specifying a format whose precision will be automatically set by the scale.

# identity.copy()

Returns an exact copy of this scale. Changes to this scale will not affect the returned scale, and vice versa.

Ordinal Scales

Unlike linear and other quantitative scales, ordinal scales have a discrete domain and range. For example, an ordinal scale might map a set of named categories to a set of colors, or determine the horizontal positions of columns in a column chart.

# ordinal()

Constructs a new ordinal scale with an empty domain and an empty range. The ordinal scale is invalid (always returning undefined) until a range is specified.

# ordinal(x)

Given a value x in the input domain, returns the corresponding value y in the output range.

If the given value x is not in the scale’s domain, and the range was specified explicitly (as by range but not rangeBands, rangeRoundBands or rangePoints), then x is implicitly added to the domain and the next-available value y in the range is assigned to x, such that this and subsequent invocations of the scale given the same x return the same y.

# ordinal.domain([domain])

If domain is specified, sets the domain of the ordinal scale to the specified array of values. The first element in domain will be mapped to the first element in the range, the second domain value to the second range value, and so on. Domain values are stored internally in an associative array as a mapping from value to index; the resulting index is then used to retrieve a value from the range. Thus, an ordinal scale's values must be coercible to a string, and the stringified version of the domain value uniquely identifies the corresponding range value. If domain is not specified, this method returns the current domain.

Setting the domain on an ordinal scale is optional. If no domain is set, a range must be set explicitly. Then, each unique value that is passed to the scale function will be assigned a new value from the range; in other words, the domain will be inferred implicitly from usage. Although domains may thus be constructed implicitly, it is still a good idea to assign the ordinal scale's domain explicitly to ensure deterministic behavior, as inferring the domain from usage will be dependent on ordering.

# ordinal.range([range])

If range is specified, sets the range of the ordinal scale to the specified array of values. The first element in the domain will be mapped to the first element in range, the second domain value to the second range value, and so on. If there are fewer elements in the range than in the domain, the scale will recycle values from the start of the range. If range is not specified, this method returns the current range.

This method is intended for when the set of discrete output values is computed explicitly, such as a set of categorical colors. In other cases, such as determining the layout of an ordinal scatterplot or bar chart, you may find the rangePoints or rangeBands operators more convenient.

# ordinal.rangePoints(interval[, padding])

Sets the range from the specified continuous interval. The array interval contains two elements representing the minimum and maximum numeric value. This interval is subdivided into n evenly-spaced points, where n is the number of (unique) values in the domain. The first and last point may be offset from the edge of the interval according to the specified padding, which defaults to zero. The padding is expressed as a multiple of the spacing between points. A reasonable value is 1.0, such that the first and last point will be offset from the minimum and maximum value by half the distance between points.

rangepoints

var s = ordinal().domain([1, 2, 3, 4]).rangePoints([0, 100]);
s.range(); // [0, 33.333333333333336, 66.66666666666667, 100]

# ordinal.rangeRoundPoints(interval[, padding])

Like rangePoints, except guarantees that the range values are integers so as to avoid antialiasing artifacts.

var s = ordinal().domain([1, 2, 3, 4]).rangeRoundPoints([0, 100]);
s.range(); // [1, 34, 67, 100]

Note that rounding necessarily introduces additional outer padding which is, on average, proportional to the length of the domain. For example, for a domain of size 50, an additional 25px of outer padding on either side may be required. Modifying the range extent to be closer to a multiple of the domain length may reduce the additional padding.

var s = ordinal().domain(range(50)).rangeRoundPoints([0, 95]);
s.range(); // [23, 24, 25, …, 70, 71, 72]
s.rangeRoundPoints([0, 100]);
s.range(); // [1, 3, 5, …, 95, 97, 98]

(Alternatively, you could round the output of the scale manually or apply shape-rendering: crispEdges. However, this will result in irregularly spaced points.)

# ordinal.rangeBands(interval[, padding[, outerPadding]])

Sets the range from the specified continuous interval. The array interval contains two elements representing the minimum and maximum numeric value. This interval is subdivided into n evenly-spaced bands, where n is the number of (unique) values in the domain. The bands may be offset from the edge of the interval and other bands according to the specified padding, which defaults to zero. The padding is typically in the range [0,1] and corresponds to the amount of space in the range interval to allocate to padding. A value of 0.5 means that the band width will be equal to the padding width. The outerPadding argument is for the entire group of bands; a value of 0 means there will be padding only between rangeBands.

rangebands

var s = ordinal().domain([1, 2, 3]).rangeBands([0, 100]);
s.rangeBand(); // 33.333333333333336
s.range(); // [0, 33.333333333333336, 66.66666666666667]
s.rangeExtent(); // [0, 100]

# ordinal.rangeRoundBands(interval[, padding[, outerPadding]])

Like rangeBands, except guarantees that range values and band width are integers so as to avoid antialiasing artifacts.

var s = ordinal().domain([1, 2, 3]).rangeRoundBands([0, 100]);
s.range(); // [1, 34, 67]
s.rangeBand(); // 33
s.rangeExtent(); // [0, 100]

Note that rounding necessarily introduces additional outer padding which is, on average, proportional to the length of the domain. For example, for a domain of size 50, an additional 25px of outer padding on either side may be required. Modifying the range extent to be closer to a multiple of the domain length may reduce the additional padding.

var s = ordinal().domain(range(50)).rangeRoundBands([0, 95]);
s.range(); // [23, 24, 25, …, 70, 71, 72]
s.rangeRoundBands([0, 100]);
s.range(); // [0, 2, 4, …, 94, 96, 98]

(Alternatively, you could round the output of the scale manually or apply shape-rendering: crispEdges. However, this will result in irregularly spaced and sized bands.)

# ordinal.rangeBand()

Returns the band width. When the scale’s range is configured with rangeBands or rangeRoundBands, the scale returns the lower value for the given input. The upper value can then be computed by offsetting by the band width. If the scale’s range is set using range or rangePoints, the band width is zero.

# ordinal.rangeExtent()

Returns a two-element array representing the extent of the scale's range, i.e., the smallest and largest values.

# ordinal.copy()

Returns an exact copy of this ordinal scale. Changes to this scale will not affect the returned scale, and vice versa.

Category Scales

# category10()

Constructs a new ordinal scale with a range of ten categorical colors.

1f77b4 #1f77b4
ff7f0e #ff7f0e
2ca02c #2ca02c
d62728 #d62728
9467bd #9467bd
8c564b #8c564b
e377c2 #e377c2
7f7f7f #7f7f7f
bcbd22 #bcbd22
17becf #17becf

# category20()

Constructs a new ordinal scale with a range of twenty categorical colors.

1f77b4 #1f77b4
aec7e8 #aec7e8
ff7f0e #ff7f0e
ffbb78 #ffbb78
2ca02c #2ca02c
98df8a #98df8a
d62728 #d62728
ff9896 #ff9896
9467bd #9467bd
c5b0d5 #c5b0d5
8c564b #8c564b
c49c94 #c49c94
e377c2 #e377c2
f7b6d2 #f7b6d2
7f7f7f #7f7f7f
c7c7c7 #c7c7c7
bcbd22 #bcbd22
dbdb8d #dbdb8d
17becf #17becf
9edae5 #9edae5

# category20b()

Constructs a new ordinal scale with a range of twenty categorical colors.

393b79 #393b79
5254a3 #5254a3
6b6ecf #6b6ecf
9c9ede #9c9ede
637939 #637939
8ca252 #8ca252
b5cf6b #b5cf6b
cedb9c #cedb9c
8c6d31 #8c6d31
bd9e39 #bd9e39
e7ba52 #e7ba52
e7cb94 #e7cb94
843c39 #843c39
ad494a #ad494a
d6616b #d6616b
e7969c #e7969c
7b4173 #7b4173
a55194 #a55194
ce6dbd #ce6dbd
de9ed6 #de9ed6

# category20c()

Constructs a new ordinal scale with a range of twenty categorical colors. This color scale includes color specifications and designs developed by Cynthia Brewer (colorbrewer.org).

3182bd #3182bd
6baed6 #6baed6
9ecae1 #9ecae1
c6dbef #c6dbef
e6550d #e6550d
fd8d3c #fd8d3c
fdae6b #fdae6b
fdd0a2 #fdd0a2
31a354 #31a354
74c476 #74c476
a1d99b #a1d99b
c7e9c0 #c7e9c0
756bb1 #756bb1
9e9ac8 #9e9ac8
bcbddc #bcbddc
dadaeb #dadaeb
636363 #636363
969696 #969696
bdbdbd #bdbdbd
d9d9d9 #d9d9d9

Changes from D3 3.x:

  • linear.ticks more often returns the right number of ticks.

  • log.ticks returns better ticks scales that are not base-10.

  • scale.domain and scale.range make defensive copies.

  • time.ticks, time.nice, utcTime.ticks and utcTime.nice no longer takes an time interval as an argument but instead takes an optional internal name, such as "seconds". For a UTC time scale, this will use the corresponding UTC time interval.

  • time.tickFormat and utcTime.tickFormat now accept an optional specifier as an alias for d3-time-format’s format and utcFormat functions.

  • time.utc has been renamed utcTime.

d3-scale's People

Contributors

jasondavies avatar mbostock avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.