CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-plotly

An open-source interactive data visualization library for Python

Pending
Overview
Eval results
Files

color-utilities.mddocs/

Color Utilities

Comprehensive color management with built-in color scales, palette generation, and color format conversion. The colors module supports sequential, diverging, cyclical, and qualitative color schemes with over 50 utility functions.

Capabilities

Color Format Conversion

Functions for converting between different color representation formats.

def hex_to_rgb(hex_color):
    """
    Convert hex color to RGB tuple.
    
    Parameters:
    - hex_color: str, hex color string (e.g., '#FF0000' or 'FF0000')
    
    Returns:
    tuple: RGB values as (r, g, b) where each value is 0-255
    """

def rgb_to_hex(rgb_tuple):
    """
    Convert RGB tuple to hex color string.
    
    Parameters:
    - rgb_tuple: tuple, RGB values as (r, g, b) where each value is 0-255
    
    Returns:
    str: Hex color string with leading '#'
    """

def convert_colors_to_same_type(colors, colortype='tuple'):
    """
    Convert list of colors to same format type.
    
    Parameters:
    - colors: list, colors in various formats (hex, rgb, named)
    - colortype: str, target format ('tuple', 'hex')
    
    Returns:
    list: Colors converted to specified format
    """

def convert_to_RGB_255(colors):
    """
    Convert colors to RGB 255 format.
    
    Parameters:
    - colors: list, colors in various formats
    
    Returns:
    list: Colors as RGB tuples with values 0-255
    """

def unconvert_from_RGB_255(colors):
    """
    Convert colors from RGB 255 format to normalized RGB.
    
    Parameters:
    - colors: list, RGB colors with values 0-255
    
    Returns:
    list: Colors as normalized RGB tuples with values 0-1
    """

def label_rgb(colors):
    """
    Add 'rgb' labels to RGB color tuples.
    
    Parameters:
    - colors: list, RGB color tuples
    
    Returns:
    list: RGB colors formatted as 'rgb(r, g, b)' strings
    """

def unlabel_rgb(colors):
    """
    Remove 'rgb' labels from RGB color strings.
    
    Parameters:
    - colors: list, RGB color strings like 'rgb(r, g, b)'
    
    Returns:
    list: RGB colors as tuples (r, g, b)
    """

Color Scale Creation and Manipulation

Functions for creating custom color scales and sampling from existing ones.

def make_colorscale(colors, position=None):
    """
    Create a custom color scale from color list.
    
    Parameters:
    - colors: list, colors for the scale (hex, rgb, or named)
    - position: list, optional positions (0-1) for each color
    
    Returns:
    list: Color scale as list of [position, color] pairs
    """

def sample_colorscale(colorscale, samplepoints, low=0.0, high=1.0, 
                     colortype='tuple'):
    """
    Sample colors from a color scale at specified points.
    
    Parameters:
    - colorscale: str or list, color scale name or custom scale
    - samplepoints: list, positions (0-1) to sample from scale
    - low: float, lower bound for sampling range
    - high: float, upper bound for sampling range  
    - colortype: str, output format ('tuple', 'hex')
    
    Returns:
    list: Sampled colors in specified format
    """

def find_intermediate_color(lowcolor, highcolor, intermed, colortype='tuple'):
    """
    Find intermediate color between two colors.
    
    Parameters:
    - lowcolor: str or tuple, starting color
    - highcolor: str or tuple, ending color
    - intermed: float, interpolation factor (0-1)
    - colortype: str, output format ('tuple', 'hex')
    
    Returns:
    str or tuple: Intermediate color in specified format
    """

def get_colorscale(name):
    """
    Get built-in color scale by name.
    
    Parameters:
    - name: str, color scale name
    
    Returns:
    list: Color scale as list of [position, color] pairs
    """

Color Validation and Parsing

Functions for validating and parsing color specifications.

def validate_colors(colors, colortype='tuple'):
    """
    Validate that colors are in correct format.
    
    Parameters:
    - colors: list, colors to validate
    - colortype: str, expected format ('tuple', 'hex')
    
    Returns:
    bool: True if all colors are valid
    
    Raises:
    PlotlyError: If colors are invalid
    """

def color_parser(colors, function):
    """
    Parse and process colors through a function.
    
    Parameters:
    - colors: list, input colors in various formats
    - function: str, processing function name
    
    Returns:
    list: Processed colors
    """

def validate_colorscale(colorscale):
    """
    Validate that colorscale is properly formatted.
    
    Parameters:
    - colorscale: list, color scale to validate
    
    Returns:
    bool: True if colorscale is valid
    
    Raises:
    PlotlyError: If colorscale is invalid
    """

Built-in Color Scales

Color scale namespaces containing predefined color schemes for different data types.

# Sequential color scales - for continuous data with natural ordering
sequential = ColorScaleNamespace([
    'Viridis', 'Plasma', 'Inferno', 'Magma', 'Cividis',
    'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 
    'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples',
    'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
    'Hot', 'Jet', 'Blackbody', 'Earth', 'Electric', 'Rainbow',
    'Portland', 'Blackbody', 'Earth', 'Electric', 'Viridis_r',
    'Plasma_r', 'Inferno_r', 'Magma_r', 'Cividis_r'
])

# Diverging color scales - for data with meaningful center point
diverging = ColorScaleNamespace([
    'RdBu', 'RdYlBu', 'RdYlGn', 'Spectral', 'BrBG', 'PiYG',
    'PRGn', 'PuOr', 'RdGy', 'Tealrose', 'Temps', 'Tropic',
    'Balance', 'HSV', 'Picnic', 'Portland', 'RdBu_r',
    'RdYlBu_r', 'RdYlGn_r', 'Spectral_r'
])

# Cyclical color scales - for periodic/circular data
cyclical = ColorScaleNamespace([
    'IceFire', 'Edge', 'HSV', 'mrybm', 'mygbm', 'Phase',
    'IceFire_r', 'Edge_r', 'HSV_r', 'mrybm_r', 'mygbm_r'
])

# Qualitative color scales - for categorical data
qualitative = ColorScaleNamespace([
    'Set1', 'Set2', 'Set3', 'Pastel1', 'Pastel2', 'Dark2',
    'Accent', 'Alphabet', 'Antique', 'Bold', 'Light24',
    'Plotly', 'Prism', 'Safe', 'Vivid', 'D3', 'G10', 'T10'
])

# Access individual scales
sequential.Viridis: list  # Viridis color scale
diverging.RdBu: list     # Red-Blue diverging scale
cyclical.IceFire: list   # Ice-Fire cyclical scale
qualitative.Set1: list   # Set1 qualitative colors

Color Scale Utilities

Additional utilities for working with color scales and palettes.

def n_colors(lowcolor, highcolor, n_colors, colortype='tuple'):
    """
    Generate n evenly spaced colors between two colors.
    
    Parameters:
    - lowcolor: str or tuple, starting color
    - highcolor: str or tuple, ending color  
    - n_colors: int, number of colors to generate
    - colortype: str, output format ('tuple', 'hex')
    
    Returns:
    list: List of n interpolated colors
    """

def colorscale_to_colors(colorscale, n_colors=None):
    """
    Extract color list from color scale.
    
    Parameters:
    - colorscale: str or list, color scale name or definition
    - n_colors: int, number of colors to extract (default: all)
    
    Returns:
    list: Colors from the color scale
    """

def colors_to_colorscale(colors):
    """
    Convert color list to color scale format.
    
    Parameters:
    - colors: list, colors to convert
    
    Returns:
    list: Color scale as [position, color] pairs
    """

def get_colorscale_names():
    """
    Get all available built-in color scale names.
    
    Returns:
    dict: Color scale names grouped by type
        - 'sequential': list of sequential scale names
        - 'diverging': list of diverging scale names  
        - 'cyclical': list of cyclical scale names
        - 'qualitative': list of qualitative scale names
    """

def swatches(colorscale=None, colors=None, template=None):
    """
    Create color swatch visualization.
    
    Parameters:
    - colorscale: str or list, color scale to visualize
    - colors: list, individual colors to visualize
    - template: str, plotly template for styling
    
    Returns:
    Figure: Plotly figure showing color swatches
    """

Named Colors

Access to standard named colors and CSS color names.

# Named color constants
PLOTLY_COLORS: list  # Default plotly color sequence
DEFAULT_PLOTLY_COLORS: list  # Legacy default colors

# CSS named colors (subset)
CSS_NAMED_COLORS = {
    'aliceblue': '#F0F8FF',
    'antiquewhite': '#FAEBD7', 
    'aqua': '#00FFFF',
    'aquamarine': '#7FFFD4',
    'azure': '#F0FFFF',
    'beige': '#F5F5DC',
    'bisque': '#FFE4C4',
    'black': '#000000',
    'blue': '#0000FF',
    'brown': '#A52A2A',
    'cyan': '#00FFFF',
    'gold': '#FFD700',
    'green': '#008000',
    'grey': '#808080',
    'magenta': '#FF00FF',
    'orange': '#FFA500',
    'pink': '#FFC0CB',
    'purple': '#800080',
    'red': '#FF0000',
    'white': '#FFFFFF',
    'yellow': '#FFFF00'
    # ... and many more
}

Usage Examples

import plotly.colors as pc
import plotly.express as px
import numpy as np

# Color format conversion
hex_color = '#FF5733'
rgb_tuple = pc.hex_to_rgb(hex_color)  # (255, 87, 51)
hex_back = pc.rgb_to_hex(rgb_tuple)   # '#FF5733'

# Create custom color scale
custom_colors = ['red', 'yellow', 'green', 'blue'] 
custom_scale = pc.make_colorscale(custom_colors)

# Sample colors from built-in scale
viridis_samples = pc.sample_colorscale('Viridis', [0, 0.25, 0.5, 0.75, 1.0])

# Find intermediate color
intermediate = pc.find_intermediate_color('red', 'blue', 0.5)  # Purple

# Generate color gradient  
gradient = pc.n_colors('lightblue', 'darkblue', 10)

# Use color scales in plots
df = px.data.tips()

# Sequential scale for continuous data
fig1 = px.scatter(df, x="total_bill", y="tip", color="size",
                 color_continuous_scale=pc.sequential.Viridis)

# Diverging scale for data with meaningful center
fig2 = px.imshow(np.random.randn(20, 20), 
                color_continuous_scale=pc.diverging.RdBu)

# Qualitative colors for categories  
fig3 = px.scatter(df, x="total_bill", y="tip", color="day",
                 color_discrete_sequence=pc.qualitative.Set1)

# Custom colorscale
fig4 = px.scatter(df, x="total_bill", y="tip", color="size",
                 color_continuous_scale=custom_scale)

# Color swatch visualization
swatch_fig = pc.swatches('Viridis')
swatch_fig.show()

# List available color scales
scale_names = pc.get_colorscale_names()
print("Sequential:", scale_names['sequential'][:5])
print("Diverging:", scale_names['diverging'][:5])
print("Qualitative:", scale_names['qualitative'][:5])

# Validate colors
colors_to_check = ['red', '#FF0000', (255, 0, 0)]
is_valid = pc.validate_colors(colors_to_check, colortype='tuple')

# Access color scale data directly
viridis_scale = pc.sequential.Viridis
print(f"Viridis has {len(viridis_scale)} color stops")

# Extract colors from scale
viridis_colors = pc.colorscale_to_colors('Viridis', n_colors=5)

# Convert colors to scale format
my_colors = ['red', 'orange', 'yellow', 'green', 'blue']
my_scale = pc.colors_to_colorscale(my_colors)

Install with Tessl CLI

npx tessl i tessl/pypi-plotly

docs

color-utilities.md

datasets.md

express-plotting.md

figure-factory.md

graph-objects.md

index.md

io-operations.md

tools-utilities.md

tile.json