### Install Detroit using pip
Source: https://detroit.readthedocs.io/en/latest/index
Installs the latest stable version of the Detroit library from PyPI using pip. Ensure you have pip installed and updated.
```bash
pip install detroit
```
--------------------------------
### Install Detroit using pip
Source: https://detroit.readthedocs.io/en/latest/_sources/index
Installs the latest stable version of the Detroit library from PyPI using pip. This is the standard method for obtaining the library.
```shell
pip install detroit
```
--------------------------------
### Quantize Scale Example - Python
Source: https://detroit.readthedocs.io/en/latest/api/scale/quantize
An example demonstrating the usage of a quantize scale. It initializes a scale using a domain and a color scheme, then iterates through a range of values, printing the input and its corresponding quantized output from the scale.
```python
>>> scale = d3.scale_quantize([0, 100], d3.SCHEME_BLUES[6])
>>> for x in range(11):
... x = 10 * x
... print(x, scale(x))
...
0 #f7fbff
10 #f7fbff
20 #deebf7
30 #c6dbef
40 #9ecae1
50 #6baed6
60 #4292c6
70 #2171b5
80 #08519c
90 #08306b
100 #08306b
```
--------------------------------
### Example: Ticks with Percentage Formatting - Python
Source: https://detroit.readthedocs.io/en/latest/api/axis
Example of generating three ticks with percentage formatting on a linear scale using the set_ticks method.
```python
>>> # To generate three ticks with percentage formatting on a linear scale :
```
--------------------------------
### Create Detroit Path Serializer
Source: https://detroit.readthedocs.io/en/latest/api/path
Initializes a path serializer with an optional number of digits for rounding. This is the primary way to start building a path.
```Python
path_serializer = detroit.path(_digits=2)
```
--------------------------------
### Example: Building an SVG structure
Source: https://detroit.readthedocs.io/en/latest/api/selection
Demonstrates chaining methods to create an SVG element with nested groups and rectangles, then printing the resulting structure.
```python
>>> body = d3.create("body")
>>> (
... body
... .append("svg")
... .attr("width", 960)
... .attr("height", 500)
... .append("g")
... .attr("transform", "translate(20, 20)")
... .append("rect")
... .attr("width", 920)
... .attr("height", 460)
... )
>>> print(body.to_string())
>>> str(body)
''
```
--------------------------------
### Detroit ScaleBand methods (Python)
Source: https://detroit.readthedocs.io/en/latest/api/scale/band
Provides examples of using various methods on a ScaleBand object, including setting the domain, range, unknown value handling, rounding, alignment, and padding.
```python
>>> scale = d3.scale_band()
>>> scale.set_domain(["a", "b", "c"])
>>> scale.set_range([0, 960])
>>> scale.set_unknown("red")
>>> scale.set_round(True)
>>> scale.set_align(0.5)
>>> scale.set_padding(0.1)
>>> scale.set_padding_inner(0.2)
>>> scale.set_padding_outer(0.3)
>>> scale.get_bandwidth()
# Output will depend on the padding settings
```
--------------------------------
### Time Scale Creation
Source: https://detroit.readthedocs.io/en/latest/api/scale/time
Demonstrates how to create a time scale using different constructor signatures and provides an example of its usage.
```APIDOC
## Detroit Time Scale API
### Description
This section details the creation and usage of time scales within the Detroit library. Time scales are specialized linear scales that operate on temporal domains, allowing for the mapping of datetime values to a numerical range.
### Constructor Overloads
`detroit.scale_time() → ScaleTime`
- Creates a time scale with default settings.
`detroit.scale_time(_range_vals : list[T]_) → ScaleTime`
- Creates a time scale with a specified range.
`detroit.scale_time(_domain : list[datetime]_, _range_vals : list[T]_) → ScaleTime`
- Builds a new time scale with the specified domain and range, using the default interpolator and disabling clamping.
### Parameters for `scale_time(_domain, _range_vals)`
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Request Example
```python
from datetime import datetime
import detroit as d3
hour = timedelta(hours=1)
scale = d3.scale_time([datetime(2000, 1, 1), datetime(2000, 1, 2)], [0, 960])
for x in range(24 + 1):
x = datetime(2000, 1, 1) + x * hour
print(x, scale(x))
```
### Response
#### Success Response (200)
- The `scale_time` function returns an instance of `ScaleTime`.
#### Response Example
```json
{
"example": "ScaleTime object"
}
```
```
--------------------------------
### Example: Create and Render Bottom Axis - JavaScript
Source: https://detroit.readthedocs.io/en/latest/api/axis
Demonstrates creating a bottom axis with a linear scale and rendering it to an SVG element using D3.js.
```javascript
>>> svg = d3.create("svg")
>>> svg.call(d3.axis_bottom(d3.scale_linear()))
Selection(
groups=[[svg]],
parents=[svg],
enter=None,
exit=None,
data={},
)
>>> print(svg.to_string())
```
--------------------------------
### Create SVG element with Detroit
Source: https://detroit.readthedocs.io/en/latest/_sources/index
Shows how to initiate the creation of an SVG element using the `d3.create()` function in the Detroit library. This is the starting point for building SVG visualizations.
```python
import detroit as d3
svg = d3.create("svg")
```
--------------------------------
### Create and use a Detroit band scale (Python)
Source: https://detroit.readthedocs.io/en/latest/api/scale/band
Demonstrates creating a band scale with a specified domain and range, and then iterating through a sequence to get scaled values. Also shows how to retrieve the bandwidth of the scale.
```python
>>> scale = d3.scale_band(["a", "b", "c"], [0, 960])
>>> for c in "abcdefgh":
... print(c, scale(c))
...
...
a 0.0
b 320.0
c 640.0
d 0.0
e 320.0
f 640.0
g 0.0
h 320.0
>>> scale.get_bandwidth()
320.0
```
--------------------------------
### Example: Using detroit.scale_linear for color interpolation
Source: https://detroit.readthedocs.io/en/latest/api/scale/linear
Demonstrates how to create a linear scale to map numerical values to colors. The example shows how to generate a scale from 0 to 100 that interpolates between 'red' and 'blue', and then prints the color for values from 0 to 100 in increments of 10.
```python
>>> scale = d3.scale_linear([0, 100], ["red", "blue"])
>>> for x in range(11):
... x = x * 10
... print(x, scale(x))
...
0 rgb(255, 0, 0)
10 rgb(230, 0, 26)
20 rgb(204, 0, 51)
30 rgb(178, 0, 76)
40 rgb(153, 0, 102)
50 rgb(128, 0, 128)
60 rgb(102, 0, 153)
70 rgb(76, 0, 178)
80 rgb(51, 0, 204)
90 rgb(26, 0, 230)
100 rgb(0, 0, 255)
```
--------------------------------
### Example: Simple element append
Source: https://detroit.readthedocs.io/en/latest/api/selection
Shows how to create an SVG element and append a 'g' element with a class attribute, then prints the updated SVG structure.
```python
>>> svg = d3.create("svg")
>>> print(svg.to_string())
>>> g = svg.append("g").attr("class", "labels")
>>> print(svg.to_string())
```
--------------------------------
### Create Nice Intervals with Detroit
Source: https://detroit.readthedocs.io/en/latest/api/array
Generates a new interval [nice_start, nice_stop] that encompasses the given interval [start, stop]. The nice_start and nice_stop values are aligned with the corresponding tick_step, ensuring clean divisions. Examples demonstrate usage with different counts.
```python
>>> d3.nice(10.2, 20.8, 10)
[10, 21]
>>> d3.nice(10.2, 20.8, 1)
[0, 50]
```
--------------------------------
### detroit.create
Source: https://detroit.readthedocs.io/en/latest/_sources/api/selection
Function to create a new selection. This is typically the starting point for data manipulation.
```APIDOC
## POST /detroit/create
### Description
Creates a new selection, often used to initialize a data manipulation process.
### Method
POST
### Endpoint
/detroit/create
### Parameters
#### Request Body
(No specific parameters are documented for the create function itself, but it likely accepts data to form the initial selection)
### Request Example
(Example would depend on the expected input data structure, e.g., a JSON array)
### Response
#### Success Response (200)
- **selection** (Selection) - The newly created selection object.
#### Response Example
(Example would be a representation of the created Selection object)
```
--------------------------------
### D3.js Join Example: Handling Enter and Update Selections
Source: https://detroit.readthedocs.io/en/latest/api/selection
Illustrates using the `onenter` and `onupdate` callbacks with the .join() method. This example dynamically adds and updates circle elements based on data, changing fill colors and adding strokes.
```python
>>> data = [None] * 3
>>> svg = d3.create("svg")
>>> svg.append("circle").attr("fill", "yellow")
Selection(
groups=[[circle]],
parents=[svg],
enter=None,
exit=None,
data={: None},
)
>>> print(svg.to_string())
>>> (
... svg.select_all("circle")
... .data(data)
... .join(
... onenter=lambda enter: enter.append("circle").attr("fill", "green"),
... onupdate=lambda update: update.attr("fill", "blue")
... )
... .attr("stroke", "black")
... )
Selection(
groups=[[circle, circle, None]],
parents=[svg],
enter=None,
exit=None,
data={: 0, : 1, : 2},
)
>>> print(svg.to_string())
```
--------------------------------
### D3.js Interpolation Example with Detroit
Source: https://detroit.readthedocs.io/en/latest/api/interpolate
This example demonstrates how to use the `detroit.interpolate` function to create a numerical interpolator and retrieve values at different points between the bounds.
```python
>>> interpolator = d3.interpolate(10, 20)
>>> interpolator(0)
10.0
>>> interpolator(1)
20.0
>>> interpolator(0.5)
15.0
```
--------------------------------
### Example of using an ordinal scale - Python
Source: https://detroit.readthedocs.io/en/latest/api/scale/ordinal
This example demonstrates how to create and use an ordinal scale in Python. It initializes a scale with a domain of characters and a range of colors. It then iterates through a string, printing each character and its corresponding color from the scale. The scale cycles through the range if the input exceeds the domain.
```python
>>> scale = d3.scale_ordinal(["a", "b", "c"], ["red", "green", "blue"])
>>> for c in "abcdefgh":
... print(c, scale(c))
...
a red
b green
c blue
d red
e green
f blue
g red
h green
```
--------------------------------
### Load and Prepare Data for Area Chart (Python)
Source: https://detroit.readthedocs.io/en/latest/_sources/area
Loads stock data (AAPL) from a URL using Polars, parses dates, and selects relevant columns. It also defines a named tuple for margin configuration. Dependencies include 'detroit' and 'polars'.
```python
# Source : https://observablehq.com/@d3/area-chart/2
import detroit as d3
import polars as pl # for data manipulation
from collections import namedtuple
URL = "https://static.observableusercontent.com/files/de259092d525c13bd10926eaf7add45b15f2771a8b39bc541a5bba1e0206add4880eb1d876be8df469328a85243b7d813a91feb8cc4966de582dc02e5f8609b7?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27aapl.csv"
Margin = namedtuple("Margin", ["top", "right", "bottom", "left"])
aapl = pl.read_csv(URL).select(
pl.col("date").str.to_datetime("%Y-%m-%d"),
pl.col("close"),
)
```
--------------------------------
### ScaleQuantize Class Methods
Source: https://detroit.readthedocs.io/en/latest/api/scale/quantize
Provides methods for interacting with a quantize scale object, including setting domain/range, getting values, and generating ticks.
```APIDOC
## ScaleQuantize Class
### Description
Provides methods for interacting with a quantize scale object.
### Methods
#### `__call__(self, x: Union[int, float, None] = None) -> T`
Given a value in the input domain, returns the corresponding value in the output range.
- **x** (Number | None) - Input value
- **Returns**: Output value (T)
#### `invert_extent(self, y: T) -> Union[int, float]`
Returns the extent of values in the domain [x0,x1] for the corresponding value in the range.
- **y** (T) - Input value
- **Returns**: Output value (Number)
#### `set_domain(self, domain: list[Union[int, float]]) -> ScaleQuantize`
Sets the scale’s domain to the specified two-element array of numbers.
- **domain** (list[Number]) - Domain
- **Returns**: Itself (ScaleQuantize)
#### `set_range(self, range_vals: list[T]) -> ScaleQuantize`
Sets the scale’s range to the specified array of values.
- **range_vals** (list[T]) - Range values
- **Returns**: Itself (ScaleQuantize)
#### `set_unknown(self, unknown: Any) -> ScaleQuantize`
Sets the scale’s unknown value.
- **unknown** (Any) - Unknown value
- **Returns**: Itself (ScaleQuantize)
#### `ticks(self, count: Optional[int] = None) -> list[Union[int, float]]`
Returns approximately count representative values from the scale’s domain.
- **count** (int | None) - Count. If specified, the scale may return more or fewer values depending on the domain.
- **Returns**: list[Number] - Tick values are uniformly spaced and have human-readable values.
#### `tick_format(self, count: Optional[int] = None, specifier: Optional[str] = None) -> Callable[[Union[int, float]], str]`
Returns a number format function suitable for displaying a tick value.
- **count** (int | None) - Count. Should match the count used for generating ticks.
- **specifier** (str | None) - Specifier.
- **Returns**: Callable[[Number], str] - Tick format function.
#### `nice(self, count: Optional[int] = None) -> ScaleQuantize`
Extends the domain so that it starts and ends on nice round values.
- **count** (int | None) - Count argument allows greater control over the step size used to extend the bounds.
- **Returns**: Itself (ScaleQuantize)
### Request Example
```python
# Assuming 'scale' is an instance of ScaleQuantize
# value = scale(50)
# extent = scale.invert_extent(color_value)
# scale.set_domain([0, 200])
# scale.set_range(['red', 'blue'])
# ticks = scale.ticks(10)
# format_func = scale.tick_format(10, '.0f')
# scale.nice()
```
### Response
#### Success Response (200)
- **ScaleQuantize** - The scale object or computed value/list.
#### Response Example
```json
{
"example": "Processed scale operation result"
}
```
```
--------------------------------
### Load Data using Polars
Source: https://detroit.readthedocs.io/en/latest/_sources/density
Loads the 'faithful' dataset from a remote URL into a Polars DataFrame. This step involves specifying the URL and the tab separator for the TSV file.
```python
# https://observablehq.com/@d3/density-contours
import detroit as d3
import polars as pl
URL = "https://static.observableusercontent.com/files/98d78d7f290f9776833e989617d49b592039ea65fee3b451764067cccd582eac122b3a07619cf223e8526910284fc105dfcb24b9af785535ee1dc6914687f9ac?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27faithful.tsv"
faithful = pl.read_csv(URL, separator="\t")
```
--------------------------------
### Create and Use a Threshold Scale (Python Example)
Source: https://detroit.readthedocs.io/en/latest/api/scale/threshold
Demonstrates how to create a threshold scale using `detroit.scale_threshold` with a specified domain and range, and then iterate through values to see their mapped outputs. This scale maps numeric inputs to categorical string outputs.
```python
import detroit as d3
# Define the domain and range for the threshold scale
domain_values = [0, 1]
range_values = ["red", "white", "blue"]
# Build the threshold scale
scale = d3.scale_threshold(domain_values, range_values)
# Example usage: iterate and print mapped values
steps = 10
for i in range(steps + 1):
x = -1 + 2 * i / steps
print(f"{x} {scale(x)}")
```
--------------------------------
### ScaleThreshold Class Methods (Python)
Source: https://detroit.readthedocs.io/en/latest/api/scale/threshold
Provides Python examples for interacting with the `ScaleThreshold` class. This includes setting the domain, range, and unknown values for a threshold scale, and demonstrating the `__call__` and `invert_extent` methods.
```python
import detroit as d3
# Initialize a ScaleThreshold object
# Assuming a default or previously set range and domain
scale = d3.ScaleThreshold()
# Set a new domain
new_domain = [0, 10, 20, 30]
scale.set_domain(new_domain)
# Set a new range
new_range = ["low", "medium", "high", "very high"]
scale.set_range(new_range)
# Set the unknown value
scale.set_unknown("N/A")
# Get the mapped value for an input
mapped_value = scale(15)
print(f"Mapped value for 15: {mapped_value}")
# Invert the extent for a range value
# Assuming 'medium' is in the range
if 'medium' in new_range:
extent = scale.invert_extent("medium")
print(f"Extent for 'medium': {extent}")
```
--------------------------------
### Create Density Chart with Detroit
Source: https://detroit.readthedocs.io/en/latest/_sources/density
Generates a density chart using the Detroit library. It configures chart dimensions, scales, computes density contours, appends axes, and adds data points (circles) to the chart.
```python
# Make data as list[dict]
fidelity = faithful.to_dicts()
# Declare the chart's dimensions.
width = 928
height = 600
margin_top = 20
margin_right = 30
margin_bottom = 30
margin_left = 40
# Create the horizontal and vertical scales.
x = (
d3.scale_linear()
.set_domain(d3.extent(faithful, lambda d: d["waiting"]))
.nice()
.set_range_round([margin_left, width - margin_right])
)
y = (
d3.scale_linear()
.set_domain(d3.extent(faithful, lambda d: d["eruptions"]))
.nice()
.set_range_round([height - margin_bottom, margin_top])
)
# Compute the density contours.
contours = (
d3.contour_density()
.x(lambda d: x(d["waiting"]))
.y(lambda d: y(d["eruptions"]))
.set_size([width, height])
.set_bandwidth(30)
.set_thresholds(30)(faithful)
)
# Create the SVG container.
svg = (
d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("view_box", f"0 0 {width} {height}")
.attr("style", "max-width: 100%; height: auto;")
)
# Append the axes.
(
svg.append("g")
.attr("transform", f"translate(0,{height - margin_bottom})")
.call(d3.axis_bottom(x).set_tick_size_outer(0))
.call(lambda g: g.select(".domain").remove())
.call(
lambda g: g.select(".tick:last-of-type text")
.clone()
.attr("y", -3)
.attr("dy", "null")
.attr("font-weight", "bold")
.text("Idle (min.)")
)
)
(
svg.append("g")
.attr("transform", f"translate({margin_left},0)")
.call(d3.axis_left(y).set_tick_size_outer(0))
.call(lambda g: g.select(".domain").remove())
.call(
lambda g: g.select(".tick:last-of-type text")
.clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("Erupting (min.)")
)
)
# Append the contours.
(
svg.append("g")
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.select_all()
.data(contours)
.join("path")
.attr("stroke-width", lambda d, i: 1 if i % 5 else 0.25)
.attr("d", d3.geo_path())
)
# Append dots.
(
svg.append("g")
.attr("stroke", "white")
.select_all()
.data(faithful)
.join("circle")
.attr("cx", lambda d: x(d["waiting"]))
.attr("cy", lambda d: y(d["eruptions"]))
.attr("r", 2)
)
```
--------------------------------
### Prepare Stacked Area Chart Data and Scales
Source: https://detroit.readthedocs.io/en/latest/_sources/stack
Prepares the data for a stacked area chart by converting it to dictionaries and defining scales for x, y, and color. It configures stacking order, offset, and keys, and creates an area shape generator.
```python
data = unemployment.to_dicts()
# Declare chart's dimensions
width = 928
height = 500
margin_top = 20
margin_right = 20
margin_bottom = 20
margin_left = 40
# Determine the series that need to be stacked.
# set_keys: distinct series keys, in input order
# set_values: get value for each series key and stack
# index: group by stack then series key
series = (
d3.stack()
.set_order(d3.stack_order_descending)
.set_offset(d3.stack_offset_expand)
.set_keys(unemployment["industry"].unique().to_list())
.set_value(lambda d, key, i, data: data[d][key]["unemployed"])(
d3.index(data, lambda d: d["date"], lambda d: d["industry"])
)
)
# Prepare the scales for positional and color encodings.
x = (
d3.scale_time()
.set_domain(d3.extent(data, lambda d: d["date"]))
.set_range([margin_left, width - margin_right])
)
y = d3.scale_linear().set_range_round([height - margin_bottom, margin_top])
color = (
d3.scale_ordinal()
.set_domain([d.key for d in series])
.set_range(d3.SCHEME_TABLEAU_10)
)
# Construct an area shape.
area = (
d3.area()
.x(lambda d: x(d.data.timestamp()))
.y0(lambda d: y(d[0]))
.y1(lambda d: y(d[1]))
)
# Create the SVG container.
svg = (
d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("view_box", [0, 0, width, height])
.attr("style", "max-width: 100% height: auto")
)
# Append a path for each series.
(
svg.append("g")
.select_all()
.data(series)
.join("path")
.attr("fill", lambda d: color(d.key))
.attr("d", area)
.append("title")
.text(lambda d: d.key)
)
# Append the x axis, and remove the domain line.
(
svg.append("g")
.attr("transform", f"translate(0, {height - margin_bottom})")
.call(d3.axis_bottom(x).set_tick_size_outer(0))
.call(lambda g: g.select(".domain").remove())
)
# Add the y axis, remove the domain line, add grid lines and a label.
(
svg.append("g")
.attr("transform", f"translate({margin_left},0)")
.call(d3.axis_left(y).set_ticks(height / 80, "%'))
.call(lambda g: g.select(".domain").remove())
.call(
lambda g:
g.select_all(".tick line")
.filter(lambda d: d == 0 or d == 1)
.clone()
.attr("x2", width - margin_left - margin_right)
)
.call(
lambda g:
g.append("text")
.attr("x", -margin_left)
.attr("y", 10)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.text("↑ Unemployed persons")
)
)
```
--------------------------------
### Create SVG Element with D3
Source: https://detroit.readthedocs.io/en/latest/api/axis
Demonstrates creating an SVG element with specified dimensions and viewBox using d3. This is a common setup for SVG visualizations.
```python
svg = (
d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", f"0 0 {width} {height}")
)
```
--------------------------------
### Load and Process Traffic Data with Polars
Source: https://detroit.readthedocs.io/en/latest/_sources/heatmap
Loads traffic data from a URL, extracts the hour from the date, calculates the median number of vehicles for each location and hour using Polars, and handles null values.
```python
from collections import namedtuple
import detroit as d3
import polars as pl
URL = "https://static.observableusercontent.com/files/609a91fa3908394198a9b2592b8432a798332e9a140a8d5f9c864615e3f18b2e822badadc579c06b394bb1396a20f064d72123b718354b829978b2d4782bd5c9?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27traffic.csv"
Margin = namedtuple("Margin", ["top", "right", "bottom", "left"])
theme = "light"
# Extract hours and get the median of vehicles for each pair (location, hour)
traffic = (
(
pl.read_csv(URL)
.select(
pl.col("location"),
pl.col("date").str.to_datetime(strict=False).dt.hour().alias("hour"),
pl.col("vehicles"),
)
.fill_null(0)
)
.group_by("location", "hour")
.agg(pl.col("vehicles").median())
)
```
--------------------------------
### Load Unemployment Data with Polars
Source: https://detroit.readthedocs.io/en/latest/_sources/stack
Loads unemployment data from a CSV file using the Polars library. It parses the 'date' column into datetime objects and selects relevant columns for further processing.
```python
# Source: https://observablehq.com/@d3/normalized-stacked-area-chart/2
import polars as pl
import detroit as d3
URL = "https://static.observableusercontent.com/files/76f13741128340cc88798c0a0b7fa5a2df8370f57554000774ab8ee9ae785ffa2903010cad670d4939af3e9c17e5e18e7e05ed2b38b848ac2fc1a0066aa0005f?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27unemployment.csv"
unemployment = pl.read_csv(URL).select(
pl.col("date").str.to_datetime("%Y-%m-%d"),
pl.all().exclude("date"),
)
```
--------------------------------
### Set Start Angle Accessor - detroit.js AreaRadial
Source: https://detroit.readthedocs.io/en/latest/api/shape/area_radial
Sets the start angle accessor function for the AreaRadial generator. This defines the starting angle for radial segments.
```python
area.start_angle(lambda d: d.start_angle)
area.start_angle(0)
```
--------------------------------
### PolygonStream Abstract Methods
Source: https://detroit.readthedocs.io/en/latest/api/geo/streams
Defines the interface for streaming polygon data. Includes methods for starting and ending polygons, lines/rings, and indicating points.
```python
_abstractmethod _line_end()_
Indicates the end of a line or ring. Within a polygon, indicates the end of a ring. Unlike GeoJSON, the redundant closing coordinate of a ring is not indicated via point, and instead is implied via lineEnd within a polygon.
_abstractmethod _line_start()_
Indicates the start of a line or ring. Within a polygon, indicates the start of a ring. The first ring of a polygon is the exterior ring, and is typically clockwise. Any subsequent rings indicate holes in the polygon, and are typically counterclockwise.
_abstractmethod _point(_x : float_, _y : float_)_
Indicates a point with the specified coordinates x and y (and optionally z). The coordinate system is unspecified and implementation-dependent; for example, projection streams require spherical coordinates in degrees as input. Outside the context of a polygon or line, a point indicates a point geometry object (Point or MultiPoint). Within a line or polygon ring, the point indicates a control point.
Parameters:
* **x** (_float_) – x value
* **y** (_float_) – y value
_abstractmethod _polygon_end()_
Indicates the end of a polygon.
_abstractmethod _polygon_start()_
Indicates the start of a polygon. The first line of a polygon indicates the exterior ring, and any subsequent lines indicate interior holes.
```
--------------------------------
### Initialize Data and SVG for Speed Comparison (Python)
Source: https://detroit.readthedocs.io/en/latest/complex_charts/kernel_comparison
Initializes dimensions, margins, and datasets for Numba and Cupy performance benchmarks. It also sets up the base SVG element for the visualization using the Detroit library.
```python
import detroit as d3
from operator import itemgetter
width = 480
height = 400
margin_top = 20
margin_right = 50
margin_bottom = 10
margin_left = 120
# Data
numba = [
(97.52, "macroscopic"),
(93.8, "equilibrium"),
(92.71, "streaming_step"),
(89.62, "collision"),
(85.13, "bounce_back"),
(6.1, "inflow"),
(5.98, "update_fin"),
(5.86, "outflow"),
]
cupy = [
(98.44, "macroscopic"),
(92.99, "streaming_step"),
(92.86, "equilibrium"),
(87.6, "collision"),
(85.1, "bounce_back"),
(5.98, "update_fin"),
(5.98, "inflow"),
(5.84, "outflow"),
]
# Initialize the content of the SVG
svg = (
d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", f"0 0 {width} {height}")
.style("max-width", "100%")
.style("height", "auto")
)
```
--------------------------------
### Calculate bins using detroit.rollups
Source: https://detroit.readthedocs.io/en/latest/api/array
Example of using detroit.rollups to group data by 'id' and sum the 'value' for each group. This is useful for aggregation tasks.
```python
detroit.rollups(
data,
lambda values: sum([d["value"] for d in values]),
lambda d: d["id"],
)
```
--------------------------------
### Create and Use a Symlog Scale
Source: https://detroit.readthedocs.io/en/latest/api/scale/symlog
Demonstrates creating a symlog scale with a specified domain and range, setting a constant, and then applying the scale to various input values. It also shows how to iterate through scale values.
```python
import detroit as d3
scale = d3.scale_symlog([0, 100], [0, 960])
scale = scale.set_constant(2)
steps = 10
print(scale(0))
print(scale(0.5))
for x in range(steps + 1):
x = 2 * x / steps
x = 10 ** x
print(x, scale(x))
```
--------------------------------
### Save Stack Area Chart to SVG File
Source: https://detroit.readthedocs.io/en/latest/_sources/stack
Saves the generated SVG chart to a file named 'stack-area.svg'. This allows the visualization to be stored and shared.
```python
with open("stack-area.svg", "w") as file:
file.write(str(svg))
```
--------------------------------
### Load Data for Scatter Chart (Python)
Source: https://detroit.readthedocs.io/en/latest/_sources/scatter
Loads car data from a CSV URL using the Polars library. It defines a schema for the data and displays the shape and a preview of the loaded DataFrame.
```python
# Source : https://observablehq.com/@d3/brushable-scatterplot
import detroit as d3
import polars as pl # for data manipulation
from collections import namedtuple
URL = "https://static.observableusercontent.com/files/53c407ee531bab128477148c9e28c49dd06bf83a93ae317e58dbb9fc819db0d4f6c4fb9646fa2fe20faad76addee20cfc360eab2362eeaec3340a5e4655b9996?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27cars-2.csv"
Margin = namedtuple("Margin", ["top", "right", "bottom", "left"])
schema = pl.Schema(
{
"Name": pl.String,
"Miles_per_Gallon": pl.Float32,
"Cylinders": pl.Int32,
"Displacement": pl.Float32,
"Horsepower": pl.Int32,
"Weight_in_lbs": pl.Int32,
"Acceleration": pl.Float32,
"Year": pl.Int32,
"Origin": pl.String,
}
)
cars = pl.read_csv(URL, schema=schema)
```
--------------------------------
### Load and Prepare Data for Bar Chart (Python)
Source: https://detroit.readthedocs.io/en/latest/_sources/bar
Loads alphabet frequency data from a CSV URL using polars and sorts it by frequency in descending order. It also defines a named tuple for margin properties, essential for chart layout. Dependencies include the 'detroit' and 'polars' libraries.
```python
# Source : https://observablehq.com/@d3/bar-chart/2
import detroit as d3
import polars as pl # for data manipulation
from collections import namedtuple
URL = "https://static.observableusercontent.com/files/09f63bb9ff086fef80717e2ea8c974f918a996d2bfa3d8773d3ae12753942c002d0dfab833d7bee1e0c9cd358cd3578c1cd0f9435595e76901508adc3964bbdc?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27alphabet.csv"
Margin = namedtuple("Margin", ["top", "right", "bottom", "left"])
alphabet = pl.read_csv(URL).sort(by="frequency", descending=True)
```
--------------------------------
### Set start angle for arc generator in Python
Source: https://detroit.readthedocs.io/en/latest/api/shape/arcs
Sets the start angle for the arc. This can be a fixed number or a function. The method returns the arc generator instance.
```python
set_start_angle(_start_angle : Callable[[...], float] | float | int_) -> Arc
```
--------------------------------
### Initialize Scale Linear in Detroit
Source: https://detroit.readthedocs.io/en/latest/index
Illustrates creating a linear scale in Detroit, defining its domain and range. Supports multiple signatures for initialization.
```python
width = 960
height = 580
margin_left = 40
margin_right = 30
margin_top = 20
margin_bottom = 30
x = d3.scale_linear([0, 10], [margin_left, width - margin_right])
# or
x = (
d3.scale_linear()
.set_domain([0, 10])
.set_range([margin_left, width - margin_right])
)
y = d3.scale_linear([0, 100], [height - margin_bottom, margin_top])
```
--------------------------------
### detroit.nice
Source: https://detroit.readthedocs.io/en/latest/api/array
Returns a new interval whose start and stop values are aligned with a tick step, covering the given interval.
```APIDOC
## detroit.nice
### Description
Returns a new interval `[nice_start, nice_stop]` covering the given interval `[start, stop]` and where `nice_start` and `nice_stop` are guaranteed to align with the corresponding `tick_step`.
### Method
N/A (Function Call)
### Endpoint
N/A
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
>>> detroit.nice(10.2, 20.8, 10)
[10, 21]
>>> detroit.nice(10.2, 20.8, 1)
[0, 50]
```
### Response
#### Success Response (tuple[T, T])
The function returns a tuple representing the aligned interval `[nice_start, nice_stop]`.
#### Response Example
```json
[10, 21]
```
```
--------------------------------
### Create Radial Line from Start Angle - detroit.js
Source: https://detroit.readthedocs.io/en/latest/api/shape/area_radial
Creates a new radial line generator based on the AreaRadial generator's current settings, using the start angle and inner radius accessors.
```python
line = area.line_start_angle()
```
--------------------------------
### Load Unemployment Data using Polars
Source: https://detroit.readthedocs.io/en/latest/_sources/histogram
Loads unemployment data from a remote CSV URL into a Polars DataFrame. It imports necessary libraries and defines constants for data handling.
```python
# Source : https://observablehq.com/@d3/histogram/2
import detroit as d3
import polars as pl # for data manipulation
from collections import namedtuple
URL = "https://static.observableusercontent.com/files/8a6057f29caa4e010854bfc31984511e074ff9042ec2a99f30924984821414fbaeb75e59654e9303db359dfa0c1052534691dac86017c4c2f992d23b874f9b6e?response-content-disposition=attachment%3Bfilename*%3DUTF-8%27%27unemployment-x.csv"
Margin = namedtuple("Margin", ["top", "right", "bottom", "left"])
unemployment = pl.read_csv(URL)
```