Colors and Data Utilities
Overview
This area contains Plotly's public color, bundled-data, serialization, optional-import, file, image, and general utility entrypoints. Most public modules are thin compatibility surfaces over _plotly_utils: plotly/…/__init__.py imports and re-exports _plotly_utils.colors, plotly/files.py re-exports _plotly_utils.files.PLOTLY_DIR and ensure_writable_plotly_dir, and plotly/optional_imports.py re-exports _plotly_utils.optional_imports.get_module. plotly/utils.py is partly a public wrapper: it re-exports _plotly_utils.utils.PlotlyJSONEncoder, NotEncodable, and get_module, re-exports _plotly_utils.data_utils.image_array_to_data_uri, and defines public helpers for pretty-printing, dictionary traversal, and Unicode normalization.
Color definitions live under _plotly_utils/colors/. _plotly_utils/…/__init__.py is the core implementation for color parsing and scale transforms: it defines DEFAULT_PLOTLY_COLORS, legacy PLOTLY_SCALES, validators such as validate_colors, validate_colors_dict, validate_scale_values, and validate_colorscale, conversion helpers such as hex_to_rgb, unlabel_rgb, label_rgb, convert_to_RGB_255, unconvert_from_RGB_255, convert_colors_to_same_type, convert_dict_colors_to_same_type, and colorscale helpers such as make_colorscale, colorscale_to_colors, colorscale_to_scale, convert_colorscale_to_rgb, get_colorscale, named_colorscales, and sample_colorscale. Color values are accepted in three main forms: CSS-like rgb(...) strings with 0-255 components, #rgb/#rrggbb hex strings, and normalized (r, g, b) tuples with 0-1 components. Conversion functions deliberately copy caller-provided lists, dictionaries, and colorscales before mutation in several paths so validation does not rewrite user input in place.
The color namespace modules are data registries with a small swatch API. _plotly_utils/…/sequential.py, diverging.py, cyclical.py, and qualitative.py expose named lists and reversed variants ending in _r; sequential.py, diverging.py, and cyclical.py are for continuous colorscales, while qualitative.py is for discrete sequences. Provider modules _plotly_utils/…/plotlyjs.py, colorbrewer.py, cmocean.py, and carto.py hold the concrete lists imported into the family modules. _plotly_utils/…/_swatches.py builds plotly.graph_objects.Figure previews: _swatches renders discrete stacked bars from module globals, _swatches_continuous renders 100-color continuous bars by colorscale name, and _swatches_cyclical renders polar previews for cyclical scales. plotly/…/__init__.py makes these functions and namespaces available as plotly.colors.* and restricts the public names through __all__.
Bundled sample datasets are served by plotly/…/__init__.py. Public functions such as gapminder, tips, iris, wind, election, carshare, stocks, experiment, medals_wide, and medals_long load compressed CSVs from plotly/package_data/datasets/<name>.csv.gz through _get_dataset. The loader validates return_type against AVAILABLE_BACKENDS = {"pandas", "polars", "pyarrow", "modin", "cudf"}, dynamically imports the backend (pyarrow.csv for pyarrow, modin.pandas for modin, otherwise the backend name), then calls backend.read_csv(filepath). Transformations are performed with narwhals.stable.v1: for example, gapminder can filter by year, cast year to datetime strings, drop centroid columns, and rename columns for pretty_names; medals_long unpivots the wide medals table. stocks, experiment, medals_wide, and medals_long guard index-specific options with BACKENDS_WITH_INDEX_SUPPORT = {"pandas", "modin", "cudf"}. election_geojson separately reads plotly/package_data/datasets/election.geojson.gz with gzip and json and returns a Python dict.
Optional dependency access is centralized in _plotly_utils/optional_imports.py. get_module(name, should_load=True) returns an imported module or None; when should_load=False, it only returns sys.modules.get(name). Failed imports are stored in _not_importable so repeated calls do not retry, and non-ImportError exceptions during optional import are logged with logger.exception before returning None. This helper is used throughout this area to keep numpy, pandas, PIL, and Sage support optional.
JSON and widget serialization utilities are split between _plotly_utils/utils.py and plotly/serializers.py. _plotly_utils/utils.PlotlyJSONEncoder subclasses json.JSONEncoder, attempts encoders in a fixed order (to_plotly_json, Sage, NumPy, pandas, datetime, date, tolist, decimal.Decimal, PIL), and post-processes encoded JSON so NaN, Infinity, and -Infinity become strict JSON null. _plotly_utils/utils.to_typed_array_spec converts supported NumPy arrays into Plotly.js typed-array specs with short dtype codes and base64 bdata; int64/uint64 arrays are downcast only when their observed min/max fit int8/int16/int32 or uint8/uint16/uint32, otherwise they are left unchanged. _plotly_utils.utils.convert_to_base64 recursively applies this conversion to homogeneous arrays except under keys skipped by is_skipped_key: geojson, layer, layers, and range. plotly/serializers.py provides ipywidget serializers: _py_to_js recursively serializes dicts and lists, turns eligible one-dimensional numeric NumPy arrays except int64/uint64 into {buffer: memoryview, dtype, shape}, turns other NumPy arrays into lists, and maps plotly.basedatatypes.Undefined to the sentinel string "_undefined_"; _js_to_py reverses only the recursive container traversal and Undefined sentinel.
Image conversion lives in _plotly_utils/data_utils.py with its pure-Python PNG fallback in _plotly_utils/png.py. image_array_to_data_uri(img, backend="pil", compression=4, ext="png") accepts uint8-like 2D greyscale, 3-channel RGB, or 4-channel RGBA arrays and returns a data:image/...;base64, URI. With backend="auto", it chooses Pillow if importable and otherwise uses the vendored PyPNG Writer and from_array; the PyPNG path supports PNG only, while JPEG output requires Pillow. _plotly_utils/png.py is a vendored PyPNG implementation exposing Image, Reader, Writer, write_chunks, and from_array, and data_utils.py uses only its writing path for fallback data URI generation.
File and miscellaneous helpers are intentionally small. _plotly_utils/files.py computes PLOTLY_DIR from the PLOTLY_DIR environment variable or ~/.plotly, then ensure_writable_plotly_dir() lazily caches whether the directory can be created and a .permission_test file can be written and removed. plotly/utils.py defines ElidedWrapper and ElidedPrettyPrinter for compact reprs of long lists, tuples, NumPy arrays, and strings; node_generator yields nested dict nodes with tuple paths; get_by_path follows list/dict paths; and decode_unicode recursively coerces dict keys and string values to str. _plotly_utils/utils.py also contains dependency-light string utilities used by validators and error messages: _natural_sort_strings, _get_int_type, cumsum, split_multichar, split_string_positions, display_string_positions, chomp_empty_strings, levenshtein, and find_closest_string.
Tests under tests/test_plotly_utils/ exercise the internal utility contract directly. tests/…/test_color_conversions.py covers hex parsing, warnings for 4- and 8-character hex strings, invalid hex lengths, RGB labeling, and interpolation. tests/…/test_colorscale_validator.py discovers named lists from _plotly_utils.colors.sequential, diverging, and cyclical and verifies that ColorscaleValidator accepts names case-insensitively and converts lists into [position, color] pairs. tests/…/test_data_utils.py forces the PyPNG backend, decodes generated data URIs with _plotly_utils.png.Reader, and verifies greyscale/RGB/RGBA round-trips and invalid compression/shape/JPEG fallback errors. tests/…/test_utils.py covers string-distance, path-position, skipped-key, and natural-sort helpers. Optional-dependency behavior is covered under tests/test_optional/: tests/…/test_utils.py verifies plotly.utils.PlotlyJSONEncoder with NumPy, pandas, datetime, decimal, PIL images, strict NaN/null handling, and _get_int_type; tests/…/test_skipped_b64_keys.py verifies that arrays nested below geojson, layers, and range are not encoded into base64 typed-array specs; and tests/…/optional_utils.py uses optional_imports.get_module to gate matplotlib-dependent helpers.
Coverage / routing
This document owns these paths:
plotly/colors/**plotly/data/**- plotly/files.py
- plotly/optional_imports.py
- plotly/serializers.py
- plotly/utils.py
_plotly_utils/colors/**- _plotly_utils/data_utils.py
- _plotly_utils/files.py
- _plotly_utils/optional_imports.py
- _plotly_utils/png.py
- _plotly_utils/utils.py
tests/test_plotly_utils/**tests/test_optional/**
Route reviews here when changes affect public plotly.colors, built-in colorscale or color-sequence definitions, color conversion/validation behavior, sample dataset access, optional dependency loading, JSON or ipywidget serialization, image data URI conversion, Plotly directory writability checks, utility string/path helpers, or tests under the owned test directories.
Coupling
- If a colorscale list is added, removed, or renamed in _plotly_utils/…/sequential.py, _plotly_utils/…/diverging.py, or _plotly_utils/…/cyclical.py, verify
_plotly_utils.basevalidators.ColorscaleValidatorbehavior and tests/…/test_colorscale_validator.py: the test discovers globals from those modules, andplotly.colors.get_colorscale/named_colorscalesread the validator'snamed_colorscalesmap rather than the legacyPLOTLY_SCALESdictionary in _plotly_utils/…/__init__.py. - If a color list should be visible through
plotly.colors.<family>, update the relevant family module import surface in _plotly_utils/…/sequential.py, diverging.py, cyclical.py, or qualitative.py; adding only to provider files such as _plotly_utils/…/carto.py, cmocean.py, colorbrewer.py, or plotlyjs.py may leave it unreachable from the family namespace and swatches. - If _plotly_utils/…/_swatches.py filtering changes, verify all family swatch functions: each family passes its
globals()and relies on_swatches/_swatches_continuous/_swatches_cyclicalexcluding private names,swatches*functions, and reversed_rvariants. - If plotly/…/__init__.py adds a dataset function, verify both the packaged file under
plotly/package_data/datasets/and_get_datasetbackend handling. Every CSV-backed function assumes the backend object has a compatibleread_csv(filepath)API, while post-load transformations are written against Narwhals and may not support indexes for all backends. - If
_plotly_utils/optional_imports.get_modulesemantics change, verify plotly/serializers.py, _plotly_utils/utils.py, plotly/utils.py, and optional tests: these callers depend onNonerather than raised import errors for absent NumPy, pandas, PIL, Sage, and matplotlib-like dependencies. - If typed-array encoding in _plotly_utils/utils.py changes, verify tests/…/test_skipped_b64_keys.py and any graph-object JSON paths that may carry GeoJSON or map layers.
convert_to_base64intentionally skips keys namedgeojson,layer,layers, andrangebecause Plotly.js does not accept the typed-array spec in those nested contracts. - If
_plotly_utils/data_utils.image_array_to_data_urichanges, verify both Pillow and PyPNG paths. The PyPNG path reshapes 3D arrays before passing rows into_plotly_utils/png.Writer, while JPEG output is only valid on the Pillow path. - If plotly/serializers.py changes the
"_undefined_"sentinel, also update any ipywidget traitlet usage that relies oncustom_serializers; the deserializer maps that exact string back toplotly.basedatatypes.Undefined.
Risks
- _plotly_utils/optional_imports.py caches failed optional imports in the module-level
_not_importableset. If a dependency is installed or made importable later in the same Python process,get_module(name)will continue returningNoneunless the cache is cleared or the process restarts; this can disable optional NumPy, pandas, PIL, Sage, or matplotlib behavior for code paths in _plotly_utils/utils.py, _plotly_utils/data_utils.py, and tests/…/optional_utils.py. _plotly_utils/colors/__init__.py::sample_colorscaledoes not independently clamp or validatesamplepointsagainst the colorscale domain. Values outside[0, 1]can select unintended endpoints throughbisect_left/negative indexing or raise indexing errors, so callers that pass user-controlled sample points should validate before calling._plotly_utils/files.py::ensure_writable_plotly_dircaches the first permission result in_file_permissions. IfPLOTLY_DIRpermissions change after the first call, later calls return the stale cached boolean and may either skip a now-valid directory or proceed assuming a directory that is no longer writable.