Skip to content

Export Formats

SVG linear gradient

Convert a scale to an SVG <linearGradient> element, either as an XML string or as an xml.etree.ElementTree element:

from xml.etree import ElementTree as ET
from polychromos.palette import Palette

# As a string
gradient_str: str = Palette.color_scale_to_svg_linear_gradient(
    color_scale=scale,
    gradient_id='my-gradient',
    start_pos=(0.0, 0.0),  # top-left
    end_pos=(1.0, 0.0),    # top-right (horizontal)
)

# As an ElementTree element
gradient_el: ET.Element = Palette.color_scale_to_svg_linear_gradient_etree(
    color_scale=scale,
    gradient_id='my-gradient',
    start_pos=(0.0, 0.0),
    end_pos=(1.0, 0.0),
)

Plotly

Convert to the [(position, color_string)] format expected by Plotly color scale arguments:

from typing import List, Tuple

plotly_scale: List[Tuple[float, str]] = Palette.color_scale_to_plotly(scale)

ANSI terminal colors

Convert any HSLColor to ANSI escape codes for colored terminal output. Perceptual LAB-space distance is used to find the closest palette color for 3-bit, 4-bit, and 8-bit modes.

from polychromos.color import HSLColor

color = HSLColor.from_abs_hsla(220, 100, 50)

ansi_3bit  = color.to_ansi_color(foreground=True, bits=3)   # 8 basic colors
ansi_4bit  = color.to_ansi_color(foreground=True, bits=4)   # 16 colors
ansi_8bit  = color.to_ansi_color(foreground=True, bits=8)   # 256 colors
ansi_24bit = color.to_ansi_color(foreground=True, bits=24)  # true color

print(f'{ansi_24bit}Colored text\033[0m')

Set foreground=False to produce a background color escape code instead.