Skip to content

Colors Module#

The cleopatra.styling.colors module provides the Colors class for working with colors — converting between formats (hex, RGB), validating color values, and getting the type of color — plus the composable "haze" data-style helpers: ready-made colormaps, value-tied alpha rendering, and a one-call multi-layer preset.

Colors Class#

The Colors class converts between different color formats (hex, RGB), validates color values, extracts colour ramps from images, and builds matplotlib colormaps.

cleopatra.styling.colors.Colors #

A class for handling and converting between different color formats.

The Colors class provides functionality for working with different color formats including hexadecimal colors, RGB colors (normalized between 0 and 1), and RGB colors (with values between 0 and 255). It supports validation, conversion, and manipulation of colors.

Attributes:

Name Type Description
color_value list[_ColorEntry]

The color values stored in the class, can be hex strings or RGB tuples.

Methods:

Name Description
get_type

Determine the type of each color (hex, rgb, rgb-normalized).

to_hex

Convert all colors to hexadecimal format.

to_rgb

Convert all colors to RGB format.

is_valid_hex

Check if each color is a valid hex color.

is_valid_rgb

Check if each color is a valid RGB color.

Examples: Create a Colors object with a hex color:

>>> from cleopatra.styling.colors import Colors
>>> hex_color = Colors("#ff0000")
>>> hex_color.color_value
['#ff0000']
>>> hex_color.get_type()
['hex']
Create a Colors object with an RGB color (values between 0 and 1):
>>> rgb_norm = Colors((0.5, 0.2, 0.8))
>>> rgb_norm.color_value
[(0.5, 0.2, 0.8)]
>>> rgb_norm.get_type()
['rgb-normalized']

Create a Colors object with an RGB color (values between 0 and 255):

>>> rgb_255 = Colors((128, 51, 204))
>>> rgb_255.color_value
[(128, 51, 204)]
>>> rgb_255.get_type()
['rgb']
Convert between color formats:
>>> hex_color.to_rgb()  # Convert hex to RGB (normalized)
[(1.0, 0.0, 0.0)]
>>> rgb_norm.to_hex()  # Convert RGB to hex
['#8033cc']

Source code in src/cleopatra/styling/colors.py
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
class Colors:
    """A class for handling and converting between different color formats.

    The Colors class provides functionality for working with different color formats
    including hexadecimal colors, RGB colors (normalized between 0 and 1), and
    RGB colors (with values between 0 and 255). It supports validation, conversion,
    and manipulation of colors.

    Attributes:
        color_value: The color values stored in the class, can be hex strings or RGB tuples.

    Methods:
        get_type(): Determine the type of each color (hex, rgb, rgb-normalized).
        to_hex(): Convert all colors to hexadecimal format.
        to_rgb(normalized=True): Convert all colors to RGB format.
        is_valid_hex(): Check if each color is a valid hex color.
        is_valid_rgb(): Check if each color is a valid RGB color.

    Examples:
    Create a Colors object with a hex color:
    ```python
    >>> from cleopatra.styling.colors import Colors
    >>> hex_color = Colors("#ff0000")
    >>> hex_color.color_value
    ['#ff0000']
    >>> hex_color.get_type()
    ['hex']

    ```
    Create a Colors object with an RGB color (values between 0 and 1):
    ```python
    >>> rgb_norm = Colors((0.5, 0.2, 0.8))
    >>> rgb_norm.color_value
    [(0.5, 0.2, 0.8)]
    >>> rgb_norm.get_type()
    ['rgb-normalized']

    ```

    Create a Colors object with an RGB color (values between 0 and 255):
    ```python
    >>> rgb_255 = Colors((128, 51, 204))
    >>> rgb_255.color_value
    [(128, 51, 204)]
    >>> rgb_255.get_type()
    ['rgb']

    ```
    Convert between color formats:
    ```python
    >>> hex_color.to_rgb()  # Convert hex to RGB (normalized)
    [(1.0, 0.0, 0.0)]
    >>> rgb_norm.to_hex()  # Convert RGB to hex
    ['#8033cc']

    ```
    """

    def __init__(
        self,
        color_value: ColorValue,
    ):
        """Initialize a Colors object with the given color value(s).

        Args:
            color_value: The color value(s) to initialize the object with. Can be:
                - A single hex color string (e.g., "#ff0000" or "ff0000")
                - A single RGB tuple with values between 0-1 (e.g., (1.0, 0.0, 0.0))
                - A single RGB tuple with values between 0-255 (e.g., (255, 0, 0))
                - A list of hex color strings
                - A list of RGB tuples

        Raises:
            ValueError: If the color_value is not a string, tuple, or list of strings/tuples.

        Notes:
        - Hex colors can be provided with or without the leading "#"
        - RGB tuples with float values between 0-1 are treated as normalized RGB
        - RGB tuples with integer values between 0-255 are treated as standard RGB
        - The class automatically detects the type of color format provided

        Examples:
        - Initialize with a hex color:

            ```python
            >>> from cleopatra.styling.colors import Colors
            >>> # With hash symbol
            >>> color1 = Colors("#ff0000")
            >>> color1.color_value
            ['#ff0000']
            >>> # Without hash symbol
            >>> color2 = Colors("ff0000")
            >>> color2.color_value
            ['ff0000']

            ```

        - Initialize with an RGB color (normalized, values between 0 and 1):

            ```python
            >>> rgb_norm = Colors((1.0, 0.0, 0.0))
            >>> rgb_norm.color_value
            [(1.0, 0.0, 0.0)]
            >>> rgb_norm.get_type()
            ['rgb-normalized']

            ```

        - Initialize with an RGB color (values between 0 and 255):

            ```python
            >>> rgb_255 = Colors((255, 0, 0))
            >>> rgb_255.color_value
            [(255, 0, 0)]
            >>> rgb_255.get_type()
            ['rgb']

            ```

        - Initialize with a list of colors:

            ```python
            >>> mixed_colors = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
            >>> mixed_colors.color_value
            ['#ff0000', (0, 255, 0), (0.0, 0.0, 1.0)]
            >>> mixed_colors.get_type()
            ['hex', 'rgb', 'rgb-normalized']

            ```
        """
        color_list: list[_ColorEntry]
        if isinstance(color_value, str) or isinstance(color_value, tuple):
            color_list = [color_value]
        elif isinstance(color_value, list):
            color_list = color_value
        else:
            raise ValueError(
                "The color_value must be a list of hex colors, list of tuples (RGB color), a single hex "
                "or single RGB tuple color."
            )

        self._color_value: list[_ColorEntry] = color_list

    @classmethod
    def create_from_image(cls, path: str | os.PathLike) -> "Colors":
        """Create a color object from an image.

        if you have an image of a color ramp, and you want to extract the colors from it, you can use this method.

        ![color-ramp](./../images/colors/color-ramp.png)

        Args:
            path: The path to the image file, as a `str` or `os.PathLike`
                (e.g. a `pathlib.Path`).

        Returns:
            Colors: A color object.

        Raises:
            FileNotFoundError: If the file does not exist.

        Examples:
        ```python
        >>> path = "examples/data/colors/color-ramp.png"
        >>> colors = Colors.create_from_image(path)
        >>> print(colors.color_value) # doctest: +SKIP
        [(9, 63, 8), (8, 68, 9), (5, 78, 7), (1, 82, 3), (0, 84, 0), (0, 85, 0), (1, 83, 0), (1, 81, 0), (1, 80, 1)

        ```
        """
        path = os.fspath(path)
        if not Path(path).exists():
            raise FileNotFoundError(f"The file {path} does not exist.")
        try:
            image = Image.open(path).convert("RGB")
        except UnidentifiedImageError:
            raise ValueError(f"The file {path} is not a valid image.")
        width, height = image.size
        color_values = cast(
            "list[_ColorEntry]",
            [image.getpixel((x, int(height / 2))) for x in range(width)],
        )

        return cls(color_values)

    def get_type(self) -> list[str]:
        """Determine the type of each color value.

        This method analyzes each color value stored in the object and determines
        its type: hex, rgb (values 0-255), or rgb-normalized (values 0-1).

        Returns:
            list[str]: A list of strings indicating the type of each color value.
                Possible values are:
                - 'hex': Hexadecimal color string
                - 'rgb': RGB tuple with values between 0-255
                - 'rgb-normalized': RGB tuple with values between 0-1

        Notes:
            The method uses the following criteria to determine color types:
            - If the value is a string and is a valid hex color, it's classified as 'hex'
            - If the value is a tuple of 3 floats between 0-1, it's classified as 'rgb-normalized'
            - If the value is a tuple of 3 integers between 0-255, it's classified as 'rgb'

        Examples:
        - Determine the type of a hex color:

            ```python
            >>> from cleopatra.styling.colors import Colors
            >>> hex_color = Colors("#23a9dd")
            >>> hex_color.get_type()
            ['hex']

            ```

        - Determine the type of an RGB color with normalized values (0-1):

            ```python
            >>> rgb_norm = Colors((0.5, 0.2, 0.8))
            >>> rgb_norm.get_type()
            ['rgb-normalized']

            ```

        - Determine the type of an RGB color with values between 0-255:

            ```python
            >>> rgb_255 = Colors((128, 51, 204))
            >>> rgb_255.get_type()
            ['rgb']

            ```

        - Determine types of mixed color formats:

            ```python
            >>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
            >>> mixed.get_type()
            ['hex', 'rgb', 'rgb-normalized']

            ```
        """
        color_type = []
        for color_i in self.color_value:
            if self._is_valid_rgb_norm(color_i):
                color_type.append("rgb-normalized")
            elif self._is_valid_rgb_255(color_i):
                color_type.append("rgb")
            elif self._is_valid_hex_i(color_i):
                color_type.append("hex")

        return color_type

    @property
    def color_value(self) -> list[_ColorEntry]:
        """Get the color values stored in the object.

        This property returns the color values that were provided when initializing
        the Colors object or set afterwards. The values can be hex color strings,
        RGB tuples with values between 0-255, or normalized RGB tuples with values
        between 0-1.

        Returns:
            list[_ColorEntry]: A list containing the color values. Each element can be:
                - A hex color string (e.g., "#ff0000" or "ff0000")
                - An RGB tuple with values between 0-255 (e.g., (255, 0, 0))
                - A normalized RGB tuple with values between 0-1 (e.g., (1.0, 0.0, 0.0))

        Examples:
        Get color values from a Colors object with hex colors:
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
        >>> hex_colors.color_value
        ['#ff0000', '#00ff00', '#0000ff']

        ```

        Get color values from a Colors object with RGB colors:
        ```python
        >>> rgb_colors = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
        >>> rgb_colors.color_value
        [(255, 0, 0), (0, 255, 0), (0, 0, 255)]

        ```
        Get color values from a Colors object with mixed color formats:
        ```python
        >>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
        >>> mixed.color_value
        ['#ff0000', (0, 255, 0), (0.0, 0.0, 1.0)]

        ```
        """
        return self._color_value

    def to_hex(self) -> list[str]:
        """Convert all color values to hexadecimal format.

        This method converts all color values stored in the object to hexadecimal format.
        RGB tuples (both normalized and 0-255 range) are converted to their hex equivalents.
        Hex colors remain unchanged.

        Returns:
            list[str]: A list of hexadecimal color strings. Each string is in the format '#RRGGBB'.

        Notes:
            - RGB tuples with values between 0-255 are first normalized to 0-1 range before conversion
            - RGB tuples with values already between 0-1 are directly converted
            - Existing hex colors are returned as-is
            - All returned hex colors include the leading '#' character

        Examples:
        Convert RGB colors to hex:
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> # RGB colors (0-255 range)
        >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
        >>> rgb_255.to_hex()
        ['#ff0000', '#00ff00', '#0000ff']

        ```
        >>> # RGB colors (normalized 0-1 range)
        >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)])
        >>> rgb_norm.to_hex()
        ['#ff0000', '#00ff00', '#0000ff']

        ```
        Convert a mix of color formats to hex:
        ```python
        >>> mixed = Colors([(128, 51, 204), "#23a9dd", (0.5, 0.2, 0.8)])
        >>> mixed.to_hex()
        ['#8033cc', '#23a9dd', '#8033cc']

        ```
        Hex colors are returned as-is:
        ```python
        >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
        >>> hex_colors.to_hex()
        ['#ff0000', '#00ff00', '#0000ff']

        ```
        """
        converted_color: list[str] = []
        color_type = self.get_type()
        for ind, color_i in enumerate(self.color_value):
            if color_type[ind] == "hex":
                converted_color.append(cast(str, color_i))
            elif color_type[ind] == "rgb":
                r, g, b = cast("tuple[float, float, float]", color_i)
                rgb_color_normalized = (r / 255, g / 255, b / 255)
                converted_color.append(mcolors.to_hex(rgb_color_normalized))
            else:
                converted_color.append(mcolors.to_hex(color_i))
        return converted_color

    def is_valid_hex(self) -> list[bool]:
        """Check if each color value is a valid hexadecimal color.

        This method checks each color value stored in the object to determine
        if it is a valid hexadecimal color string.

        Returns:
            list[bool]: A list of boolean values, one for each color value in the object.
                True indicates the color is a valid hex color, False otherwise.

        Notes:
            - The method uses matplotlib's is_color_like function to validate hex colors
            - Both formats with and without the leading '#' are supported
            - RGB tuples will return False as they are not hex colors

        Examples:
        Check if hex colors are valid:
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
        >>> hex_colors.is_valid_hex()
        [True, True, True]

        ```
        Check if RGB colors are valid hex colors (they're not):
        ```python
        >>> rgb_colors = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
        >>> rgb_colors.is_valid_hex()
        [False, False, False]

        ```
        Check a mix of color formats:
        ```python
        >>> mixed = Colors(["#ff0000", (0, 255, 0), "not-a-color"])
        >>> mixed.is_valid_hex()
        [True, False, False]

        ```
        """
        return [self._is_valid_hex_i(col) for col in self.color_value]

    @staticmethod
    def _is_valid_hex_i(hex_color: _ColorEntry) -> bool:
        """Check if a single color value is a valid hexadecimal color.

        This static method checks if the provided color value is a valid
        hexadecimal color string.

        Args:
            hex_color: A color string to validate as a hexadecimal color.
                Can be in the format "#RRGGBB" or "RRGGBB".

        Returns:
            bool: True if the color is a valid hexadecimal color, False otherwise.

        Notes:
            - The method uses matplotlib's is_color_like function to validate hex colors
            - Both formats with and without the leading '#' are supported
            - Non-string values will return False

        Examples:
        Check valid hex colors:
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> Colors._is_valid_hex_i("#ff0000")
        True
        >>> Colors._is_valid_hex_i("00ff00")
        False
        >>> Colors._is_valid_hex_i("#0000FF")
        True

        ```

        Check invalid hex colors:
        ```python
        >>> Colors._is_valid_hex_i("not-a-color")
        False
        >>> Colors._is_valid_hex_i("#12345")  # Too short
        False
        >>> Colors._is_valid_hex_i((255, 0, 0))  # doctest: +ELLIPSIS
        False

        ```
        """
        return isinstance(hex_color, str) and mcolors.is_color_like(hex_color)

    def is_valid_rgb(self) -> list[bool]:
        """Check if each color value is a valid RGB color.

        This method checks each color value stored in the object to determine
        if it is a valid RGB color tuple (either with values between 0-255 or
        normalized values between 0-1).

        Returns:
            list[bool]: A list of boolean values, one for each color value in the object.
                True indicates the color is a valid RGB tuple, False otherwise.

        Notes:
            - The method checks for both RGB formats: values between 0-255 and normalized values between 0-1
            - A valid RGB tuple must have exactly 3 values (R, G, B)
            - Hex color strings will return False as they are not RGB tuples

        Examples:
        Check if RGB colors are valid:
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> # RGB colors (0-255 range)
        >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
        >>> rgb_255.is_valid_rgb()
        [True, True, True]

        >>> # RGB colors (normalized 0-1 range)
        >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)])
        >>> rgb_norm.is_valid_rgb()
        [True, True, True]

        ```
        Check if hex colors are valid RGB colors (they're not):
        ```python
        >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
        >>> hex_colors.is_valid_rgb()
        [False, False, False]

        ```
        Check a mix of color formats:
        ```python
        >>> mixed = Colors([(255, 0, 0), "#00ff00", (0.0, 0.0, 1.0)])
        >>> mixed.is_valid_rgb()
        [True, False, True]

        ```
        """
        return [
            self._is_valid_rgb_norm(col) or self._is_valid_rgb_255(col)
            for col in self.color_value
        ]

    @staticmethod
    def _is_valid_rgb_255(rgb_tuple: Any) -> bool:
        """Check if a single color value is a valid RGB tuple with values between 0-255.

        This static method checks if the provided value is a valid RGB tuple with
        integer values between 0 and 255.

        Args:
            rgb_tuple: The value to check. Should be a tuple of 3 integers between 0 and 255
                to be considered valid.

        Returns:
            bool: True if the value is a valid RGB tuple with values between 0-255,
                False otherwise.

        Examples:
        Check valid RGB tuples (0-255 range):
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> Colors._is_valid_rgb_255((255, 0, 0))
        True
        >>> Colors._is_valid_rgb_255((128, 64, 32))
        True
        >>> Colors._is_valid_rgb_255((0, 0, 0))
        True

        ```
        Check invalid RGB tuples:
        ```python
        >>> Colors._is_valid_rgb_255((1.0, 0.0, 0.0))  # Floats, not integers
        False
        >>> Colors._is_valid_rgb_255((256, 0, 0))  # Value > 255
        False
        >>> Colors._is_valid_rgb_255((0, 0))  # Not 3 values
        False
        >>> Colors._is_valid_rgb_255("#ff0000")  # Not a tuple
        False

        ```
        """
        return (
            isinstance(rgb_tuple, tuple)
            and len(rgb_tuple) == 3
            and all(isinstance(value, int) for value in rgb_tuple)
            and all(0 <= value <= 255 for value in rgb_tuple)
        )

    @staticmethod
    def _is_valid_rgb_norm(rgb_tuple: Any) -> bool:
        """Check if a single color value is a valid normalized RGB tuple with values between 0-1.

        This static method checks if the provided value is a valid RGB tuple with
        float values between 0.0 and 1.0.

        Args:
            rgb_tuple: The value to check. Should be a tuple of 3 floats between 0.0 and 1.0
                to be considered valid.

        Returns:
            bool: True if the value is a valid normalized RGB tuple with values between 0.0-1.0,
                False otherwise.

        Examples:
        Check valid normalized RGB tuples:
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> Colors._is_valid_rgb_norm((1.0, 0.0, 0.0))
        True
        >>> Colors._is_valid_rgb_norm((0.5, 0.5, 0.5))
        True
        >>> Colors._is_valid_rgb_norm((0.0, 0.0, 0.0))
        True

        ```
        Check invalid normalized RGB tuples:
        ```python
        >>> Colors._is_valid_rgb_norm((255, 0, 0))  # Integers, not floats
        False
        >>> Colors._is_valid_rgb_norm((1.2, 0.0, 0.0))  # Value > 1.0
        False
        >>> Colors._is_valid_rgb_norm((0.5, 0.5))  # Not 3 values
        False
        >>> Colors._is_valid_rgb_norm("#ff0000")  # Not a tuple
        False

        ```
        """
        return (
            isinstance(rgb_tuple, tuple)
            and len(rgb_tuple) == 3
            and all(isinstance(value, float) for value in rgb_tuple)
            and all(0.0 <= value <= 1.0 for value in rgb_tuple)
        )

    def to_rgb(
        self, normalized: bool = True
    ) -> list[tuple[int | float, int | float, int | float]]:
        """Convert all color values to RGB format.

        This method converts all color values stored in the object to RGB format.
        Hex colors are converted to their RGB equivalents. RGB colors remain unchanged
        but may be normalized or denormalized based on the 'normalized' parameter.

        Args:
            normalized: Whether to return normalized RGB values (between 0 and 1) or standard RGB values
                (between 0 and 255). Defaults to True.
                - If True, returns RGB values scaled between 0 and 1
                - If False, returns RGB values scaled between 0 and 255

        Returns:
            list[tuple[int | float, int | float, int | float]]: A list of RGB tuples.
                Each tuple contains three values (R, G, B).
                - If normalized=True, values are floats between 0.0 and 1.0
                - If normalized=False, values are integers between 0 and 255

        Examples:
        - Convert hex colors to normalized RGB (0-1 range):
            ```python
            >>> from cleopatra.styling.colors import Colors
            >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
            >>> hex_colors.to_rgb(normalized=True)
            [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]

            ```

        - Convert hex colors to standard RGB (0-255 range):
            ```python
            >>> hex_colors.to_rgb(normalized=False)
            [(255, 0, 0), (0, 255, 0), (0, 0, 255)]

            ```
        - Convert RGB colors and maintain their format:
            There are two types of RGB coor values (0-255), and (0-1), you can get the RGB values in any format, the
            default is the normalized format (0-1):

            ```python
            >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0)])
            >>> rgb_255.to_rgb(normalized=False)  # Keep as 0-255 range
            [(255, 0, 0), (0, 255, 0)]
            >>> rgb_255.to_rgb(normalized=True)  # Convert to 0-1 range
            [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]

            >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)])
            >>> rgb_norm.to_rgb(normalized=True)  # Keep as 0-1 range
            [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
            >>> rgb_norm.to_rgb(normalized=False)  # Convert to 0-255 range
            [(255, 0, 0), (0, 255, 0)]

            ```

        Convert mixed color formats:
        ```python
        >>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
        >>> mixed.to_rgb(normalized=True)
        [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]

        ```
        """
        color_type = self.get_type()
        rgb: list[tuple[int | float, int | float, int | float]] = []
        if normalized:
            for ind, color_i in enumerate(self.color_value):
                if color_type[ind] == "rgb":
                    r, g, b = cast("tuple[float, float, float]", color_i)
                    rgb.append((r / 255, g / 255, b / 255))
                else:
                    rgb.append(mcolors.to_rgb(color_i))
        else:
            for ind, color_i in enumerate(self.color_value):
                if color_type[ind] == "rgb":
                    rgb.append(cast("tuple[int, int, int]", color_i))
                else:
                    r, g, b = mcolors.to_rgb(color_i)
                    rgb.append((int(r * 255), int(g * 255), int(b * 255)))

        return rgb

    def get_color_map(self, name: str | None = None) -> Colormap:
        """Get color ramp from a color values in stored in the object.

        Args:
            name: The name of the color ramp. Defaults to None.

        Returns:
            Colormap: A color map.

        Examples:
        - Create a color object from an image and get the color ramp:
            ```python
            >>> path = "examples/data/colors/color-ramp.png"
            >>> colors = Colors.create_from_image(path)
            >>> color_ramp = colors.get_color_map()
            >>> print(color_ramp) # doctest: +SKIP
            <matplotlib.colors.LinearSegmentedColormap object at 0x7f8a2e1b5e50>

            ```
        """
        vals = self.to_rgb(normalized=True)
        name = "custom_color_map" if name is None else name
        return LinearSegmentedColormap.from_list(name, vals)

color_value property #

Get the color values stored in the object.

This property returns the color values that were provided when initializing the Colors object or set afterwards. The values can be hex color strings, RGB tuples with values between 0-255, or normalized RGB tuples with values between 0-1.

Returns:

Type Description
list[_ColorEntry]

list[_ColorEntry]: A list containing the color values. Each element can be: - A hex color string (e.g., "#ff0000" or "ff0000") - An RGB tuple with values between 0-255 (e.g., (255, 0, 0)) - A normalized RGB tuple with values between 0-1 (e.g., (1.0, 0.0, 0.0))

Examples: Get color values from a Colors object with hex colors:

>>> from cleopatra.styling.colors import Colors
>>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
>>> hex_colors.color_value
['#ff0000', '#00ff00', '#0000ff']

Get color values from a Colors object with RGB colors:

>>> rgb_colors = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
>>> rgb_colors.color_value
[(255, 0, 0), (0, 255, 0), (0, 0, 255)]
Get color values from a Colors object with mixed color formats:
>>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
>>> mixed.color_value
['#ff0000', (0, 255, 0), (0.0, 0.0, 1.0)]

__init__(color_value) #

Initialize a Colors object with the given color value(s).

Parameters:

Name Type Description Default
color_value ColorValue

The color value(s) to initialize the object with. Can be: - A single hex color string (e.g., "#ff0000" or "ff0000") - A single RGB tuple with values between 0-1 (e.g., (1.0, 0.0, 0.0)) - A single RGB tuple with values between 0-255 (e.g., (255, 0, 0)) - A list of hex color strings - A list of RGB tuples

required

Raises:

Type Description
ValueError

If the color_value is not a string, tuple, or list of strings/tuples.

Notes: - Hex colors can be provided with or without the leading "#" - RGB tuples with float values between 0-1 are treated as normalized RGB - RGB tuples with integer values between 0-255 are treated as standard RGB - The class automatically detects the type of color format provided

Examples: - Initialize with a hex color:

```python
>>> from cleopatra.styling.colors import Colors
>>> # With hash symbol
>>> color1 = Colors("#ff0000")
>>> color1.color_value
['#ff0000']
>>> # Without hash symbol
>>> color2 = Colors("ff0000")
>>> color2.color_value
['ff0000']

```
  • Initialize with an RGB color (normalized, values between 0 and 1):

    >>> rgb_norm = Colors((1.0, 0.0, 0.0))
    >>> rgb_norm.color_value
    [(1.0, 0.0, 0.0)]
    >>> rgb_norm.get_type()
    ['rgb-normalized']
    
  • Initialize with an RGB color (values between 0 and 255):

    >>> rgb_255 = Colors((255, 0, 0))
    >>> rgb_255.color_value
    [(255, 0, 0)]
    >>> rgb_255.get_type()
    ['rgb']
    
  • Initialize with a list of colors:

    >>> mixed_colors = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
    >>> mixed_colors.color_value
    ['#ff0000', (0, 255, 0), (0.0, 0.0, 1.0)]
    >>> mixed_colors.get_type()
    ['hex', 'rgb', 'rgb-normalized']
    
Source code in src/cleopatra/styling/colors.py
def __init__(
    self,
    color_value: ColorValue,
):
    """Initialize a Colors object with the given color value(s).

    Args:
        color_value: The color value(s) to initialize the object with. Can be:
            - A single hex color string (e.g., "#ff0000" or "ff0000")
            - A single RGB tuple with values between 0-1 (e.g., (1.0, 0.0, 0.0))
            - A single RGB tuple with values between 0-255 (e.g., (255, 0, 0))
            - A list of hex color strings
            - A list of RGB tuples

    Raises:
        ValueError: If the color_value is not a string, tuple, or list of strings/tuples.

    Notes:
    - Hex colors can be provided with or without the leading "#"
    - RGB tuples with float values between 0-1 are treated as normalized RGB
    - RGB tuples with integer values between 0-255 are treated as standard RGB
    - The class automatically detects the type of color format provided

    Examples:
    - Initialize with a hex color:

        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> # With hash symbol
        >>> color1 = Colors("#ff0000")
        >>> color1.color_value
        ['#ff0000']
        >>> # Without hash symbol
        >>> color2 = Colors("ff0000")
        >>> color2.color_value
        ['ff0000']

        ```

    - Initialize with an RGB color (normalized, values between 0 and 1):

        ```python
        >>> rgb_norm = Colors((1.0, 0.0, 0.0))
        >>> rgb_norm.color_value
        [(1.0, 0.0, 0.0)]
        >>> rgb_norm.get_type()
        ['rgb-normalized']

        ```

    - Initialize with an RGB color (values between 0 and 255):

        ```python
        >>> rgb_255 = Colors((255, 0, 0))
        >>> rgb_255.color_value
        [(255, 0, 0)]
        >>> rgb_255.get_type()
        ['rgb']

        ```

    - Initialize with a list of colors:

        ```python
        >>> mixed_colors = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
        >>> mixed_colors.color_value
        ['#ff0000', (0, 255, 0), (0.0, 0.0, 1.0)]
        >>> mixed_colors.get_type()
        ['hex', 'rgb', 'rgb-normalized']

        ```
    """
    color_list: list[_ColorEntry]
    if isinstance(color_value, str) or isinstance(color_value, tuple):
        color_list = [color_value]
    elif isinstance(color_value, list):
        color_list = color_value
    else:
        raise ValueError(
            "The color_value must be a list of hex colors, list of tuples (RGB color), a single hex "
            "or single RGB tuple color."
        )

    self._color_value: list[_ColorEntry] = color_list

create_from_image(path) classmethod #

Create a color object from an image.

if you have an image of a color ramp, and you want to extract the colors from it, you can use this method.

color-ramp

Parameters:

Name Type Description Default
path str | PathLike

The path to the image file, as a str or os.PathLike (e.g. a pathlib.Path).

required

Returns:

Name Type Description
Colors Colors

A color object.

Raises:

Type Description
FileNotFoundError

If the file does not exist.

Examples:

>>> path = "examples/data/colors/color-ramp.png"
>>> colors = Colors.create_from_image(path)
>>> print(colors.color_value) # doctest: +SKIP
[(9, 63, 8), (8, 68, 9), (5, 78, 7), (1, 82, 3), (0, 84, 0), (0, 85, 0), (1, 83, 0), (1, 81, 0), (1, 80, 1)

Source code in src/cleopatra/styling/colors.py
@classmethod
def create_from_image(cls, path: str | os.PathLike) -> "Colors":
    """Create a color object from an image.

    if you have an image of a color ramp, and you want to extract the colors from it, you can use this method.

    ![color-ramp](./../images/colors/color-ramp.png)

    Args:
        path: The path to the image file, as a `str` or `os.PathLike`
            (e.g. a `pathlib.Path`).

    Returns:
        Colors: A color object.

    Raises:
        FileNotFoundError: If the file does not exist.

    Examples:
    ```python
    >>> path = "examples/data/colors/color-ramp.png"
    >>> colors = Colors.create_from_image(path)
    >>> print(colors.color_value) # doctest: +SKIP
    [(9, 63, 8), (8, 68, 9), (5, 78, 7), (1, 82, 3), (0, 84, 0), (0, 85, 0), (1, 83, 0), (1, 81, 0), (1, 80, 1)

    ```
    """
    path = os.fspath(path)
    if not Path(path).exists():
        raise FileNotFoundError(f"The file {path} does not exist.")
    try:
        image = Image.open(path).convert("RGB")
    except UnidentifiedImageError:
        raise ValueError(f"The file {path} is not a valid image.")
    width, height = image.size
    color_values = cast(
        "list[_ColorEntry]",
        [image.getpixel((x, int(height / 2))) for x in range(width)],
    )

    return cls(color_values)

get_color_map(name=None) #

Get color ramp from a color values in stored in the object.

Parameters:

Name Type Description Default
name str | None

The name of the color ramp. Defaults to None.

None

Returns:

Name Type Description
Colormap Colormap

A color map.

Examples:

  • Create a color object from an image and get the color ramp:
    >>> path = "examples/data/colors/color-ramp.png"
    >>> colors = Colors.create_from_image(path)
    >>> color_ramp = colors.get_color_map()
    >>> print(color_ramp) # doctest: +SKIP
    <matplotlib.colors.LinearSegmentedColormap object at 0x7f8a2e1b5e50>
    
Source code in src/cleopatra/styling/colors.py
def get_color_map(self, name: str | None = None) -> Colormap:
    """Get color ramp from a color values in stored in the object.

    Args:
        name: The name of the color ramp. Defaults to None.

    Returns:
        Colormap: A color map.

    Examples:
    - Create a color object from an image and get the color ramp:
        ```python
        >>> path = "examples/data/colors/color-ramp.png"
        >>> colors = Colors.create_from_image(path)
        >>> color_ramp = colors.get_color_map()
        >>> print(color_ramp) # doctest: +SKIP
        <matplotlib.colors.LinearSegmentedColormap object at 0x7f8a2e1b5e50>

        ```
    """
    vals = self.to_rgb(normalized=True)
    name = "custom_color_map" if name is None else name
    return LinearSegmentedColormap.from_list(name, vals)

get_type() #

Determine the type of each color value.

This method analyzes each color value stored in the object and determines its type: hex, rgb (values 0-255), or rgb-normalized (values 0-1).

Returns:

Type Description
list[str]

list[str]: A list of strings indicating the type of each color value. Possible values are: - 'hex': Hexadecimal color string - 'rgb': RGB tuple with values between 0-255 - 'rgb-normalized': RGB tuple with values between 0-1

Notes

The method uses the following criteria to determine color types: - If the value is a string and is a valid hex color, it's classified as 'hex' - If the value is a tuple of 3 floats between 0-1, it's classified as 'rgb-normalized' - If the value is a tuple of 3 integers between 0-255, it's classified as 'rgb'

Examples: - Determine the type of a hex color:

```python
>>> from cleopatra.styling.colors import Colors
>>> hex_color = Colors("#23a9dd")
>>> hex_color.get_type()
['hex']

```
  • Determine the type of an RGB color with normalized values (0-1):

    >>> rgb_norm = Colors((0.5, 0.2, 0.8))
    >>> rgb_norm.get_type()
    ['rgb-normalized']
    
  • Determine the type of an RGB color with values between 0-255:

    >>> rgb_255 = Colors((128, 51, 204))
    >>> rgb_255.get_type()
    ['rgb']
    
  • Determine types of mixed color formats:

    >>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
    >>> mixed.get_type()
    ['hex', 'rgb', 'rgb-normalized']
    
Source code in src/cleopatra/styling/colors.py
def get_type(self) -> list[str]:
    """Determine the type of each color value.

    This method analyzes each color value stored in the object and determines
    its type: hex, rgb (values 0-255), or rgb-normalized (values 0-1).

    Returns:
        list[str]: A list of strings indicating the type of each color value.
            Possible values are:
            - 'hex': Hexadecimal color string
            - 'rgb': RGB tuple with values between 0-255
            - 'rgb-normalized': RGB tuple with values between 0-1

    Notes:
        The method uses the following criteria to determine color types:
        - If the value is a string and is a valid hex color, it's classified as 'hex'
        - If the value is a tuple of 3 floats between 0-1, it's classified as 'rgb-normalized'
        - If the value is a tuple of 3 integers between 0-255, it's classified as 'rgb'

    Examples:
    - Determine the type of a hex color:

        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> hex_color = Colors("#23a9dd")
        >>> hex_color.get_type()
        ['hex']

        ```

    - Determine the type of an RGB color with normalized values (0-1):

        ```python
        >>> rgb_norm = Colors((0.5, 0.2, 0.8))
        >>> rgb_norm.get_type()
        ['rgb-normalized']

        ```

    - Determine the type of an RGB color with values between 0-255:

        ```python
        >>> rgb_255 = Colors((128, 51, 204))
        >>> rgb_255.get_type()
        ['rgb']

        ```

    - Determine types of mixed color formats:

        ```python
        >>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
        >>> mixed.get_type()
        ['hex', 'rgb', 'rgb-normalized']

        ```
    """
    color_type = []
    for color_i in self.color_value:
        if self._is_valid_rgb_norm(color_i):
            color_type.append("rgb-normalized")
        elif self._is_valid_rgb_255(color_i):
            color_type.append("rgb")
        elif self._is_valid_hex_i(color_i):
            color_type.append("hex")

    return color_type

is_valid_hex() #

Check if each color value is a valid hexadecimal color.

This method checks each color value stored in the object to determine if it is a valid hexadecimal color string.

Returns:

Type Description
list[bool]

list[bool]: A list of boolean values, one for each color value in the object. True indicates the color is a valid hex color, False otherwise.

Notes
  • The method uses matplotlib's is_color_like function to validate hex colors
  • Both formats with and without the leading '#' are supported
  • RGB tuples will return False as they are not hex colors

Examples: Check if hex colors are valid:

>>> from cleopatra.styling.colors import Colors
>>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
>>> hex_colors.is_valid_hex()
[True, True, True]
Check if RGB colors are valid hex colors (they're not):
>>> rgb_colors = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
>>> rgb_colors.is_valid_hex()
[False, False, False]
Check a mix of color formats:
>>> mixed = Colors(["#ff0000", (0, 255, 0), "not-a-color"])
>>> mixed.is_valid_hex()
[True, False, False]

Source code in src/cleopatra/styling/colors.py
def is_valid_hex(self) -> list[bool]:
    """Check if each color value is a valid hexadecimal color.

    This method checks each color value stored in the object to determine
    if it is a valid hexadecimal color string.

    Returns:
        list[bool]: A list of boolean values, one for each color value in the object.
            True indicates the color is a valid hex color, False otherwise.

    Notes:
        - The method uses matplotlib's is_color_like function to validate hex colors
        - Both formats with and without the leading '#' are supported
        - RGB tuples will return False as they are not hex colors

    Examples:
    Check if hex colors are valid:
    ```python
    >>> from cleopatra.styling.colors import Colors
    >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
    >>> hex_colors.is_valid_hex()
    [True, True, True]

    ```
    Check if RGB colors are valid hex colors (they're not):
    ```python
    >>> rgb_colors = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
    >>> rgb_colors.is_valid_hex()
    [False, False, False]

    ```
    Check a mix of color formats:
    ```python
    >>> mixed = Colors(["#ff0000", (0, 255, 0), "not-a-color"])
    >>> mixed.is_valid_hex()
    [True, False, False]

    ```
    """
    return [self._is_valid_hex_i(col) for col in self.color_value]

is_valid_rgb() #

Check if each color value is a valid RGB color.

This method checks each color value stored in the object to determine if it is a valid RGB color tuple (either with values between 0-255 or normalized values between 0-1).

Returns:

Type Description
list[bool]

list[bool]: A list of boolean values, one for each color value in the object. True indicates the color is a valid RGB tuple, False otherwise.

Notes
  • The method checks for both RGB formats: values between 0-255 and normalized values between 0-1
  • A valid RGB tuple must have exactly 3 values (R, G, B)
  • Hex color strings will return False as they are not RGB tuples

Examples: Check if RGB colors are valid:

>>> from cleopatra.styling.colors import Colors
>>> # RGB colors (0-255 range)
>>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
>>> rgb_255.is_valid_rgb()
[True, True, True]

>>> # RGB colors (normalized 0-1 range)
>>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)])
>>> rgb_norm.is_valid_rgb()
[True, True, True]
Check if hex colors are valid RGB colors (they're not):
>>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
>>> hex_colors.is_valid_rgb()
[False, False, False]
Check a mix of color formats:
>>> mixed = Colors([(255, 0, 0), "#00ff00", (0.0, 0.0, 1.0)])
>>> mixed.is_valid_rgb()
[True, False, True]

Source code in src/cleopatra/styling/colors.py
def is_valid_rgb(self) -> list[bool]:
    """Check if each color value is a valid RGB color.

    This method checks each color value stored in the object to determine
    if it is a valid RGB color tuple (either with values between 0-255 or
    normalized values between 0-1).

    Returns:
        list[bool]: A list of boolean values, one for each color value in the object.
            True indicates the color is a valid RGB tuple, False otherwise.

    Notes:
        - The method checks for both RGB formats: values between 0-255 and normalized values between 0-1
        - A valid RGB tuple must have exactly 3 values (R, G, B)
        - Hex color strings will return False as they are not RGB tuples

    Examples:
    Check if RGB colors are valid:
    ```python
    >>> from cleopatra.styling.colors import Colors
    >>> # RGB colors (0-255 range)
    >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
    >>> rgb_255.is_valid_rgb()
    [True, True, True]

    >>> # RGB colors (normalized 0-1 range)
    >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)])
    >>> rgb_norm.is_valid_rgb()
    [True, True, True]

    ```
    Check if hex colors are valid RGB colors (they're not):
    ```python
    >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
    >>> hex_colors.is_valid_rgb()
    [False, False, False]

    ```
    Check a mix of color formats:
    ```python
    >>> mixed = Colors([(255, 0, 0), "#00ff00", (0.0, 0.0, 1.0)])
    >>> mixed.is_valid_rgb()
    [True, False, True]

    ```
    """
    return [
        self._is_valid_rgb_norm(col) or self._is_valid_rgb_255(col)
        for col in self.color_value
    ]

to_hex() #

Convert all color values to hexadecimal format.

This method converts all color values stored in the object to hexadecimal format. RGB tuples (both normalized and 0-255 range) are converted to their hex equivalents. Hex colors remain unchanged.

Returns:

Type Description
list[str]

list[str]: A list of hexadecimal color strings. Each string is in the format '#RRGGBB'.

Notes
  • RGB tuples with values between 0-255 are first normalized to 0-1 range before conversion
  • RGB tuples with values already between 0-1 are directly converted
  • Existing hex colors are returned as-is
  • All returned hex colors include the leading '#' character

Examples: Convert RGB colors to hex:

>>> from cleopatra.styling.colors import Colors
>>> # RGB colors (0-255 range)
>>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
>>> rgb_255.to_hex()
['#ff0000', '#00ff00', '#0000ff']

RGB colors (normalized 0-1 range)#

rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]) rgb_norm.to_hex() ['#ff0000', '#00ff00', '#0000ff']

Convert a mix of color formats to hex:
```python
>>> mixed = Colors([(128, 51, 204), "#23a9dd", (0.5, 0.2, 0.8)])
>>> mixed.to_hex()
['#8033cc', '#23a9dd', '#8033cc']
Hex colors are returned as-is:
>>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
>>> hex_colors.to_hex()
['#ff0000', '#00ff00', '#0000ff']

Source code in src/cleopatra/styling/colors.py
def to_hex(self) -> list[str]:
    """Convert all color values to hexadecimal format.

    This method converts all color values stored in the object to hexadecimal format.
    RGB tuples (both normalized and 0-255 range) are converted to their hex equivalents.
    Hex colors remain unchanged.

    Returns:
        list[str]: A list of hexadecimal color strings. Each string is in the format '#RRGGBB'.

    Notes:
        - RGB tuples with values between 0-255 are first normalized to 0-1 range before conversion
        - RGB tuples with values already between 0-1 are directly converted
        - Existing hex colors are returned as-is
        - All returned hex colors include the leading '#' character

    Examples:
    Convert RGB colors to hex:
    ```python
    >>> from cleopatra.styling.colors import Colors
    >>> # RGB colors (0-255 range)
    >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
    >>> rgb_255.to_hex()
    ['#ff0000', '#00ff00', '#0000ff']

    ```
    >>> # RGB colors (normalized 0-1 range)
    >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)])
    >>> rgb_norm.to_hex()
    ['#ff0000', '#00ff00', '#0000ff']

    ```
    Convert a mix of color formats to hex:
    ```python
    >>> mixed = Colors([(128, 51, 204), "#23a9dd", (0.5, 0.2, 0.8)])
    >>> mixed.to_hex()
    ['#8033cc', '#23a9dd', '#8033cc']

    ```
    Hex colors are returned as-is:
    ```python
    >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
    >>> hex_colors.to_hex()
    ['#ff0000', '#00ff00', '#0000ff']

    ```
    """
    converted_color: list[str] = []
    color_type = self.get_type()
    for ind, color_i in enumerate(self.color_value):
        if color_type[ind] == "hex":
            converted_color.append(cast(str, color_i))
        elif color_type[ind] == "rgb":
            r, g, b = cast("tuple[float, float, float]", color_i)
            rgb_color_normalized = (r / 255, g / 255, b / 255)
            converted_color.append(mcolors.to_hex(rgb_color_normalized))
        else:
            converted_color.append(mcolors.to_hex(color_i))
    return converted_color

to_rgb(normalized=True) #

Convert all color values to RGB format.

This method converts all color values stored in the object to RGB format. Hex colors are converted to their RGB equivalents. RGB colors remain unchanged but may be normalized or denormalized based on the 'normalized' parameter.

Parameters:

Name Type Description Default
normalized bool

Whether to return normalized RGB values (between 0 and 1) or standard RGB values (between 0 and 255). Defaults to True. - If True, returns RGB values scaled between 0 and 1 - If False, returns RGB values scaled between 0 and 255

True

Returns:

Type Description
list[tuple[int | float, int | float, int | float]]

list[tuple[int | float, int | float, int | float]]: A list of RGB tuples. Each tuple contains three values (R, G, B). - If normalized=True, values are floats between 0.0 and 1.0 - If normalized=False, values are integers between 0 and 255

Examples:

  • Convert hex colors to normalized RGB (0-1 range):

    >>> from cleopatra.styling.colors import Colors
    >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
    >>> hex_colors.to_rgb(normalized=True)
    [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]
    

  • Convert hex colors to standard RGB (0-255 range):

    >>> hex_colors.to_rgb(normalized=False)
    [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
    

  • Convert RGB colors and maintain their format: There are two types of RGB coor values (0-255), and (0-1), you can get the RGB values in any format, the default is the normalized format (0-1):

    >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0)])
    >>> rgb_255.to_rgb(normalized=False)  # Keep as 0-255 range
    [(255, 0, 0), (0, 255, 0)]
    >>> rgb_255.to_rgb(normalized=True)  # Convert to 0-1 range
    [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
    
    >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)])
    >>> rgb_norm.to_rgb(normalized=True)  # Keep as 0-1 range
    [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
    >>> rgb_norm.to_rgb(normalized=False)  # Convert to 0-255 range
    [(255, 0, 0), (0, 255, 0)]
    

Convert mixed color formats:

>>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
>>> mixed.to_rgb(normalized=True)
[(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]

Source code in src/cleopatra/styling/colors.py
def to_rgb(
    self, normalized: bool = True
) -> list[tuple[int | float, int | float, int | float]]:
    """Convert all color values to RGB format.

    This method converts all color values stored in the object to RGB format.
    Hex colors are converted to their RGB equivalents. RGB colors remain unchanged
    but may be normalized or denormalized based on the 'normalized' parameter.

    Args:
        normalized: Whether to return normalized RGB values (between 0 and 1) or standard RGB values
            (between 0 and 255). Defaults to True.
            - If True, returns RGB values scaled between 0 and 1
            - If False, returns RGB values scaled between 0 and 255

    Returns:
        list[tuple[int | float, int | float, int | float]]: A list of RGB tuples.
            Each tuple contains three values (R, G, B).
            - If normalized=True, values are floats between 0.0 and 1.0
            - If normalized=False, values are integers between 0 and 255

    Examples:
    - Convert hex colors to normalized RGB (0-1 range):
        ```python
        >>> from cleopatra.styling.colors import Colors
        >>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
        >>> hex_colors.to_rgb(normalized=True)
        [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]

        ```

    - Convert hex colors to standard RGB (0-255 range):
        ```python
        >>> hex_colors.to_rgb(normalized=False)
        [(255, 0, 0), (0, 255, 0), (0, 0, 255)]

        ```
    - Convert RGB colors and maintain their format:
        There are two types of RGB coor values (0-255), and (0-1), you can get the RGB values in any format, the
        default is the normalized format (0-1):

        ```python
        >>> rgb_255 = Colors([(255, 0, 0), (0, 255, 0)])
        >>> rgb_255.to_rgb(normalized=False)  # Keep as 0-255 range
        [(255, 0, 0), (0, 255, 0)]
        >>> rgb_255.to_rgb(normalized=True)  # Convert to 0-1 range
        [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]

        >>> rgb_norm = Colors([(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)])
        >>> rgb_norm.to_rgb(normalized=True)  # Keep as 0-1 range
        [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
        >>> rgb_norm.to_rgb(normalized=False)  # Convert to 0-255 range
        [(255, 0, 0), (0, 255, 0)]

        ```

    Convert mixed color formats:
    ```python
    >>> mixed = Colors(["#ff0000", (0, 255, 0), (0.0, 0.0, 1.0)])
    >>> mixed.to_rgb(normalized=True)
    [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]

    ```
    """
    color_type = self.get_type()
    rgb: list[tuple[int | float, int | float, int | float]] = []
    if normalized:
        for ind, color_i in enumerate(self.color_value):
            if color_type[ind] == "rgb":
                r, g, b = cast("tuple[float, float, float]", color_i)
                rgb.append((r / 255, g / 255, b / 255))
            else:
                rgb.append(mcolors.to_rgb(color_i))
    else:
        for ind, color_i in enumerate(self.color_value):
            if color_type[ind] == "rgb":
                rgb.append(cast("tuple[int, int, int]", color_i))
            else:
                r, g, b = mcolors.to_rgb(color_i)
                rgb.append((int(r * 255), int(g * 255), int(b * 255)))

    return rgb

Composable data styles ("haze")#

These module-level helpers render one or more value layers with per-pixel opacity tied to value — the CAMS aerosol look — without constructing a glyph. They pair with projection.apply_projection_style to compose the same style on a flat map or an orthographic globe.

  • HAZE_COLORMAPS — ready LinearSegmentedColormap objects ("organic_matter", "dust"); white → saturated hue, not registered in matplotlib's global registry.
  • DATA_STYLES — named data-style presets; "haze" maps each layer to a colormap, label, and value/alpha limits.
  • alpha_scaled_image — draw a 2D array with imshow where low values fade to transparent (NaN is always fully transparent).
  • alpha_scaled_mesh — the pcolormesh / curvilinear-grid counterpart, for orthographic_grid output.
  • apply_data_style — draw one or more named layers with a DATA_STYLES preset (colour + swatch legend) in one call; returns the artists keyed by layer name.
import matplotlib
matplotlib.use("Agg")  # any backend
import matplotlib.pyplot as plt
import numpy as np

from cleopatra.styling.colors import apply_data_style

# two synthetic aerosol layers on a lon/lat grid
yy, xx = np.mgrid[0:90, 0:180]
organic_matter = np.exp(-(((xx - 60) ** 2) / 400.0 + ((yy - 55) ** 2) / 200.0))
dust = np.exp(-(((xx - 80) ** 2) / 300.0 + ((yy - 35) ** 2) / 150.0))

fig, ax = plt.subplots(figsize=(6, 4))
artists = apply_data_style(
    ax,
    {"organic_matter": organic_matter, "dust": dust},
    style="haze",
    extent=[-180, 180, -90, 90],
    origin="lower",
)

cleopatra.styling.colors.apply_data_style(ax, layers, style='haze', *, x=None, y=None, legend=True, legend_bounds=None, swatch_text_color='white', swatch_value_color=None, swatch_box=None, **render_kwargs) #

Draw one or more named data layers with a registered DATA_STYLES preset.

Applies alpha_scaled_image (and, if legend, a stacked swatch_legend per layer) to each array in layers, using the colormap/label/range that style defines for that layer name in DATA_STYLES. Calling this with layers={"organic_matter": ..., "dust": ...} reproduces the CAMS aerosol look in one call -- but it is only a thin orchestration over alpha_scaled_image + swatch_legend, so nothing about it requires the orthographic globe: it works on a plain flat axes, an existing "light"/"dark" reference map (cleopatra.basemap.geo), or any other projection just as well. Pass x/y (e.g. from cleopatra.basemap.projection.orthographic_grid) to render on a curvilinear grid via alpha_scaled_mesh instead of the default imshow-based alpha_scaled_image.

Parameters:

Name Type Description Default
ax Axes

Axes to draw on.

required
layers dict[str, ndarray]

Mapping of layer name to its 2D data array. Every key must be a layer defined by style (e.g. "organic_matter"/"dust" for "haze"); pass a subset to draw only some of a style's layers. For a categorical preset (one that defines categories, e.g. "flow_direction_d8"), the array is matched to the declared class codes by exact float equality, so it must be integer-coded (D8 powers of two, flood classes 0..4 — all exactly representable in float). Any cell that is not bit-exactly a declared code (nodata, sinks, or a value perturbed by a lossy float transform) is treated as out-of-range and rendered transparent.

required
style str

A name from DATA_STYLES. Defaults to "haze".

'haze'
x ndarray | None

Optional 2D curvilinear x-coordinates (see alpha_scaled_mesh). When given (together with y), every layer is drawn with alpha_scaled_mesh instead of alpha_scaled_image.

None
y ndarray | None

Optional 2D curvilinear y-coordinates, paired with x.

None
legend bool

If True (default), attach one swatch_legend per layer, stacked top-to-bottom in the top-left.

True
legend_bounds list[tuple[float, float, float, float]] | None

Explicit (x0, y0, width, height) per layer legend, in the same order as layers, overriding the auto-stacked default.

None
swatch_text_color str

Colour of each swatch legend's title, by default "white".

'white'
swatch_value_color str | None

Optional colour for the swatch endpoint values, by default None (reuse swatch_text_color).

None
swatch_box bool | str | dict | None

Optional opaque backing panel behind each swatch legend (True / colour / dict), by default None (none).

None
**render_kwargs Any

Forwarded to every alpha_scaled_image (or alpha_scaled_mesh, when x/y are given) call. A vmin/vmax/center/cmap/extend/levels/bands/alpha/ alpha_range here overrides just that field of the preset (the rest of the preset is kept), routed through resolve_style_overrides so the field-interaction rules hold (bands replaces levels; alpha and alpha_range are mutually exclusive). A string norm ("log"/"symlog") overrides the preset's norm kind and a Normalize instance is used directly as the colour norm. None of these override keys leak on to the underlying imshow/pcolormesh call.

{}

Returns:

Type Description
dict[str, Any]

dict[str, Any]: The image (or mesh) artist for each layer, keyed by

dict[str, Any]

name, in the same order as layers.

Raises:

Type Description
KeyError

If style is not registered, or layers names a layer the style does not define.

ValueError

If exactly one of x/y is given (they must be given together, or both omitted).

Examples:

  • Draw both haze layers and read back the images and their labels:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from cleopatra.styling.colors import apply_data_style
    >>> fig, ax = plt.subplots()
    >>> layers = {
    ...     "dust": np.array([[0.0, 1.0]]),
    ...     "organic_matter": np.array([[0.2, 0.8]]),
    ... }
    >>> images = apply_data_style(ax, layers)
    >>> sorted(images)
    ['dust', 'organic_matter']
    >>> [t.get_text() for c in ax.child_axes for t in c.texts][:2]
    ['Dust', '0']
    >>> plt.close(fig)
    
  • Passing x/y renders on a curvilinear mesh instead of imshow:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from matplotlib.collections import QuadMesh
    >>> from cleopatra.styling.colors import apply_data_style
    >>> fig, ax = plt.subplots()
    >>> x, y = np.meshgrid(np.arange(3), np.arange(3))
    >>> images = apply_data_style(
    ...     ax, {"dust": np.array([[0.0, 1.0], [0.5, 1.0]])},
    ...     x=x, y=y, shading="flat",
    ... )
    >>> isinstance(images["dust"], QuadMesh)
    True
    >>> plt.close(fig)
    
  • An unknown layer name raises KeyError before drawing anything:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from cleopatra.styling.colors import apply_data_style
    >>> fig, ax = plt.subplots()
    >>> apply_data_style(ax, {"smoke": np.array([[0.0, 1.0]])})
    Traceback (most recent call last):
        ...
    KeyError: "['smoke'] not defined for data style 'haze'; available layers: ['dust', 'organic_matter']"
    >>> plt.close(fig)
    
See Also

alpha_scaled_image: The regular-grid rendering primitive this composes. alpha_scaled_mesh: The curvilinear-grid rendering primitive this composes when x/y are given. swatch_legend: The per-layer legend primitive this composes. cleopatra.basemap.projection.apply_projection_style: The companion projection-style axis (globe vs flat).

Source code in src/cleopatra/styling/colors.py
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
def apply_data_style(
    ax: Axes,
    layers: dict[str, np.ndarray],
    style: str = "haze",
    *,
    x: np.ndarray | None = None,
    y: np.ndarray | None = None,
    legend: bool = True,
    legend_bounds: list[tuple[float, float, float, float]] | None = None,
    swatch_text_color: str = "white",
    swatch_value_color: str | None = None,
    swatch_box: bool | str | dict | None = None,
    **render_kwargs: Any,
) -> dict[str, Any]:
    """Draw one or more named data layers with a registered `DATA_STYLES` preset.

    Applies `alpha_scaled_image` (and, if `legend`, a stacked `swatch_legend`
    per layer) to each array in `layers`, using the colormap/label/range that
    `style` defines for that layer name in `DATA_STYLES`. Calling this with
    `layers={"organic_matter": ..., "dust": ...}` reproduces the CAMS
    aerosol look in one call -- but it is only a thin orchestration over
    `alpha_scaled_image` + `swatch_legend`, so nothing about it requires the
    orthographic globe: it works on a plain flat axes, an existing
    `"light"`/`"dark"` reference map (`cleopatra.basemap.geo`), or any other
    projection just as well. Pass `x`/`y` (e.g. from
    `cleopatra.basemap.projection.orthographic_grid`) to render on a curvilinear grid
    via `alpha_scaled_mesh` instead of the default `imshow`-based
    `alpha_scaled_image`.

    Args:
        ax: Axes to draw on.
        layers: Mapping of layer name to its 2D data array. Every key must be
            a layer defined by `style` (e.g. `"organic_matter"`/`"dust"` for
            `"haze"`); pass a subset to draw only some of a style's layers.
            For a **categorical** preset (one that defines `categories`, e.g.
            `"flow_direction_d8"`), the array is matched to the declared class
            codes by exact float equality, so it must be integer-coded (D8
            powers of two, flood classes 0..4 — all exactly representable in
            float). Any cell that is not bit-exactly a declared code (nodata,
            sinks, or a value perturbed by a lossy float transform) is treated
            as out-of-range and rendered transparent.
        style: A name from `DATA_STYLES`. Defaults to `"haze"`.
        x: Optional 2D curvilinear x-coordinates (see `alpha_scaled_mesh`).
            When given (together with `y`), every layer is drawn with
            `alpha_scaled_mesh` instead of `alpha_scaled_image`.
        y: Optional 2D curvilinear y-coordinates, paired with `x`.
        legend: If `True` (default), attach one `swatch_legend` per layer,
            stacked top-to-bottom in the top-left.
        legend_bounds: Explicit `(x0, y0, width, height)` per layer legend,
            in the same order as `layers`, overriding the auto-stacked
            default.
        swatch_text_color: Colour of each swatch legend's title, by default
            `"white"`.
        swatch_value_color: Optional colour for the swatch endpoint values, by
            default `None` (reuse `swatch_text_color`).
        swatch_box: Optional opaque backing panel behind each swatch legend
            (`True` / colour / dict), by default `None` (none).
        **render_kwargs: Forwarded to every `alpha_scaled_image` (or
            `alpha_scaled_mesh`, when `x`/`y` are given) call. A
            `vmin`/`vmax`/`center`/`cmap`/`extend`/`levels`/`bands`/`alpha`/
            `alpha_range` here overrides just that field of the preset (the
            rest of the preset is kept), routed through
            `resolve_style_overrides` so the field-interaction rules hold
            (`bands` replaces `levels`; `alpha` and `alpha_range` are mutually
            exclusive). A string `norm` (`"log"`/`"symlog"`) overrides the
            preset's norm kind and a `Normalize` instance is used directly as
            the colour norm. None of these override keys leak on to the
            underlying `imshow`/`pcolormesh` call.

    Returns:
        dict[str, Any]: The image (or mesh) artist for each layer, keyed by
        name, in the same order as `layers`.

    Raises:
        KeyError: If `style` is not registered, or `layers` names a layer the
            style does not define.
        ValueError: If exactly one of `x`/`y` is given (they must be given
            together, or both omitted).

    Examples:
        - Draw both haze layers and read back the images and their labels:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> from cleopatra.styling.colors import apply_data_style
            >>> fig, ax = plt.subplots()
            >>> layers = {
            ...     "dust": np.array([[0.0, 1.0]]),
            ...     "organic_matter": np.array([[0.2, 0.8]]),
            ... }
            >>> images = apply_data_style(ax, layers)
            >>> sorted(images)
            ['dust', 'organic_matter']
            >>> [t.get_text() for c in ax.child_axes for t in c.texts][:2]
            ['Dust', '0']
            >>> plt.close(fig)

            ```
        - Passing `x`/`y` renders on a curvilinear mesh instead of `imshow`:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> from matplotlib.collections import QuadMesh
            >>> from cleopatra.styling.colors import apply_data_style
            >>> fig, ax = plt.subplots()
            >>> x, y = np.meshgrid(np.arange(3), np.arange(3))
            >>> images = apply_data_style(
            ...     ax, {"dust": np.array([[0.0, 1.0], [0.5, 1.0]])},
            ...     x=x, y=y, shading="flat",
            ... )
            >>> isinstance(images["dust"], QuadMesh)
            True
            >>> plt.close(fig)

            ```
        - An unknown layer name raises `KeyError` before drawing anything:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> from cleopatra.styling.colors import apply_data_style
            >>> fig, ax = plt.subplots()
            >>> apply_data_style(ax, {"smoke": np.array([[0.0, 1.0]])})
            Traceback (most recent call last):
                ...
            KeyError: "['smoke'] not defined for data style 'haze'; available layers: ['dust', 'organic_matter']"
            >>> plt.close(fig)

            ```

    See Also:
        alpha_scaled_image: The regular-grid rendering primitive this composes.
        alpha_scaled_mesh: The curvilinear-grid rendering primitive this
            composes when `x`/`y` are given.
        swatch_legend: The per-layer legend primitive this composes.
        cleopatra.basemap.projection.apply_projection_style: The companion
            projection-style axis (globe vs flat).
    """
    if style not in DATA_STYLES:
        raise KeyError(
            f"Unknown data style {style!r}; available: {sorted(DATA_STYLES)}"
        )
    preset = DATA_STYLES[style]
    unknown = sorted(set(layers) - set(preset))
    if unknown:
        raise KeyError(
            f"{unknown} not defined for data style {style!r}; "
            f"available layers: {sorted(preset)}"
        )
    if (x is None) != (y is None):
        raise ValueError(
            "x and y must be given together (or both omitted); got "
            f"x={'given' if x is not None else None}, "
            f"y={'given' if y is not None else None}"
        )

    curvilinear = x is not None and y is not None
    if curvilinear:
        render_kwargs.setdefault("shading", "flat")
    norm_override = render_kwargs.pop("norm", None)
    raw_overrides = {
        key: render_kwargs.pop(key, None)
        for key in (
            "vmin", "vmax", "center", "cmap",
            "extend", "levels", "bands", "alpha", "alpha_range",
        )
    }
    if isinstance(norm_override, str):
        raw_overrides["norm"] = norm_override
        norm_override = None
    style_override = resolve_style_overrides(raw_overrides)
    images: dict[str, Any] = {}
    for i, (name, data) in enumerate(layers.items()):
        cfg = {**preset[name], **style_override}
        data = np.asarray(data, dtype=float)

        categories = cfg.get("categories")
        if categories is not None:
            cats = sorted(categories, key=lambda c: c[0])
            cat_values = [float(c[0]) for c in cats]
            cat_colors = [c[1] for c in cats]
            cat_labels = [c[2] for c in cats]
            cat_cmap = mcolors.ListedColormap(cat_colors)
            cat_norm = mcolors.BoundaryNorm(
                category_boundaries(cat_values), len(cat_colors)
            )
            cat_data = np.where(np.isin(data, cat_values), data, np.nan)
            if curvilinear:
                assert x is not None and y is not None
                images[name] = alpha_scaled_mesh(
                    ax,
                    x,
                    y,
                    cat_data,
                    cat_cmap,
                    norm=cat_norm,
                    constant_alpha=1.0,
                    **render_kwargs,
                )
            else:
                images[name] = alpha_scaled_image(
                    ax,
                    cat_data,
                    cat_cmap,
                    norm=cat_norm,
                    constant_alpha=1.0,
                    **render_kwargs,
                )
            if legend:
                prior_legend = ax.get_legend()
                if legend_bounds is not None:
                    x0, y0 = legend_bounds[i][0], legend_bounds[i][1]
                    leg = disjoint_legend(
                        ax,
                        cat_colors,
                        cat_labels,
                        title=cfg["label"],
                        loc="upper left",
                        bbox_to_anchor=(x0, y0),
                    )
                else:
                    leg = disjoint_legend(
                        ax,
                        cat_colors,
                        cat_labels,
                        title=cfg["label"],
                        loc="upper right",
                    )
                if prior_legend is not None and prior_legend is not leg:
                    ax.add_artist(prior_legend)
            continue

        norm, resolved_vmin, resolved_vmax = resolve_style_norm(data, cfg)
        if norm_override is not None:
            norm = norm_override
            finite = data[np.isfinite(data)]
            data_lo = float(finite.min()) if finite.size else resolved_vmin
            data_hi = float(finite.max()) if finite.size else resolved_vmax
            resolved_vmin = norm.vmin if norm.vmin is not None else data_lo
            resolved_vmax = norm.vmax if norm.vmax is not None else data_hi

        alpha_const = cfg.get("alpha")
        alpha_vmin = cfg.get("alpha_vmin")
        alpha_vmax = cfg.get("alpha_vmax")
        if alpha_const is not None and (
            alpha_vmin is not None or alpha_vmax is not None
        ):
            raise ValueError(
                f"data style layer {name!r} sets both a constant 'alpha' and "
                "'alpha_vmin'/'alpha_vmax'; those are mutually exclusive"
            )
        alpha_norm = (
            mcolors.Normalize(vmin=alpha_vmin, vmax=alpha_vmax)
            if alpha_vmin is not None or alpha_vmax is not None
            else None
        )
        if curvilinear:
            assert x is not None and y is not None
            images[name] = alpha_scaled_mesh(
                ax,
                x,
                y,
                data,
                cfg["cmap"],
                norm=norm,
                alpha_norm=alpha_norm,
                constant_alpha=alpha_const,
                **render_kwargs,
            )
        else:
            images[name] = alpha_scaled_image(
                ax,
                data,
                cfg["cmap"],
                norm=norm,
                alpha_norm=alpha_norm,
                constant_alpha=alpha_const,
                **render_kwargs,
            )
        if legend:
            bounds = (
                legend_bounds[i]
                if legend_bounds is not None
                else (0.02, 0.92 - 0.12 * i, 0.32, 0.06)
            )
            vmin_prefix, vmax_prefix = swatch_extend_prefixes(norm)
            swatch_legend(
                ax,
                resolve_colormap(cfg["cmap"]),
                cfg["label"],
                vmin=resolved_vmin,
                vmax=resolved_vmax,
                vmin_prefix=vmin_prefix,
                vmax_prefix=vmax_prefix,
                bounds=bounds,
                norm=norm,
                text_color=swatch_text_color,
                value_color=swatch_value_color,
                box=swatch_box,
            )
    return images

cleopatra.styling.colors.alpha_scaled_image(ax, data, cmap, *, norm=None, alpha_norm=None, constant_alpha=None, **imshow_kwargs) #

Draw data on ax with per-pixel opacity tied to its value.

Builds an RGBA image from cmap(norm(data)) and overwrites the alpha channel with alpha_norm(data), so low values fade toward fully transparent instead of being drawn at full opacity in a pale colour. This is the "smoke fading into haze" look used by CAMS aerosol animations: whatever is plotted underneath (a basemap, another layer) shows through wherever the value is near zero. Any non-finite entry in data (NaN) is drawn fully transparent regardless of alpha_norm.

This is a generic rendering primitive -- it takes any 2D array and any colormap, so it composes with any other cleopatra or matplotlib styling (a different basemap, a different colormap, a flat or projected axes).

Parameters:

Name Type Description Default
ax Axes

Axes to draw on.

required
data ndarray

2D array of values to map.

required
cmap str | Colormap

Colormap name or object, e.g. HAZE_COLORMAPS["dust"].

required
norm Normalize | None

Normalization mapping data to colour. Defaults to Normalize(vmin, vmax) over the finite range of data.

None
alpha_norm Normalize | None

Normalization mapping data to opacity. Defaults to norm, so colour and opacity are driven by the same scale; pass a separate instance to decouple them (e.g. a steeper alpha ramp so faint values vanish sooner than their colour would suggest).

None
constant_alpha float | None

If given, draw every finite cell at this fixed opacity (clipped to [0, 1]) and ignore alpha_norm -- e.g. 1.0 for a plain opaque field. Non-finite (NaN) cells stay transparent.

None
**imshow_kwargs Any

Forwarded to ax.imshow (e.g. extent, origin, zorder, interpolation).

{}

Returns:

Name Type Description
AxesImage AxesImage

The image artist added to ax.

Raises:

Type Description
ValueError

If data is not 2-dimensional.

Examples:

  • Low values fade to transparent, high values are opaque:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from cleopatra.styling.colors import alpha_scaled_image, HAZE_COLORMAPS
    >>> fig, ax = plt.subplots()
    >>> data = np.array([[0.0, 1.0], [0.5, 1.0]])
    >>> img = alpha_scaled_image(ax, data, HAZE_COLORMAPS["dust"])
    >>> rgba = img.get_array()
    >>> rgba[0, 0, 3]  # value 0.0 -> fully transparent
    np.float64(0.0)
    >>> rgba[0, 1, 3]  # value 1.0 -> fully opaque
    np.float64(1.0)
    >>> plt.close(fig)
    
  • NaN pixels are always transparent, independent of alpha_norm:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from cleopatra.styling.colors import alpha_scaled_image
    >>> fig, ax = plt.subplots()
    >>> data = np.array([[np.nan, 1.0]])
    >>> img = alpha_scaled_image(ax, data, "viridis")
    >>> img.get_array()[0, 0, 3]
    np.float64(0.0)
    >>> plt.close(fig)
    
See Also

HAZE_COLORMAPS: Ready-made colormaps designed for this function. swatch_legend: A matching two-stop legend for the same data.

Source code in src/cleopatra/styling/colors.py
def alpha_scaled_image(
    ax: Axes,
    data: np.ndarray,
    cmap: str | Colormap,
    *,
    norm: mcolors.Normalize | None = None,
    alpha_norm: mcolors.Normalize | None = None,
    constant_alpha: float | None = None,
    **imshow_kwargs: Any,
) -> AxesImage:
    """Draw `data` on `ax` with per-pixel opacity tied to its value.

    Builds an RGBA image from `cmap(norm(data))` and overwrites the alpha
    channel with `alpha_norm(data)`, so low values fade toward fully
    transparent instead of being drawn at full opacity in a pale colour.
    This is the "smoke fading into haze" look used by CAMS aerosol
    animations: whatever is plotted underneath (a basemap, another layer)
    shows through wherever the value is near zero. Any non-finite entry in
    `data` (NaN) is drawn fully transparent regardless of `alpha_norm`.

    This is a generic rendering primitive -- it takes any 2D array and any
    colormap, so it composes with any other cleopatra or matplotlib styling
    (a different basemap, a different colormap, a flat or projected axes).

    Args:
        ax: Axes to draw on.
        data: 2D array of values to map.
        cmap: Colormap name or object, e.g. `HAZE_COLORMAPS["dust"]`.
        norm: Normalization mapping `data` to colour. Defaults to
            `Normalize(vmin, vmax)` over the finite range of `data`.
        alpha_norm: Normalization mapping `data` to opacity. Defaults to
            `norm`, so colour and opacity are driven by the same scale; pass
            a separate instance to decouple them (e.g. a steeper alpha ramp
            so faint values vanish sooner than their colour would suggest).
        constant_alpha: If given, draw every finite cell at this fixed opacity
            (clipped to `[0, 1]`) and ignore `alpha_norm` -- e.g. `1.0` for a
            plain opaque field. Non-finite (NaN) cells stay transparent.
        **imshow_kwargs: Forwarded to `ax.imshow` (e.g. `extent`, `origin`,
            `zorder`, `interpolation`).

    Returns:
        AxesImage: The image artist added to `ax`.

    Raises:
        ValueError: If `data` is not 2-dimensional.

    Examples:
        - Low values fade to transparent, high values are opaque:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> from cleopatra.styling.colors import alpha_scaled_image, HAZE_COLORMAPS
            >>> fig, ax = plt.subplots()
            >>> data = np.array([[0.0, 1.0], [0.5, 1.0]])
            >>> img = alpha_scaled_image(ax, data, HAZE_COLORMAPS["dust"])
            >>> rgba = img.get_array()
            >>> rgba[0, 0, 3]  # value 0.0 -> fully transparent
            np.float64(0.0)
            >>> rgba[0, 1, 3]  # value 1.0 -> fully opaque
            np.float64(1.0)
            >>> plt.close(fig)

            ```
        - NaN pixels are always transparent, independent of `alpha_norm`:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> from cleopatra.styling.colors import alpha_scaled_image
            >>> fig, ax = plt.subplots()
            >>> data = np.array([[np.nan, 1.0]])
            >>> img = alpha_scaled_image(ax, data, "viridis")
            >>> img.get_array()[0, 0, 3]
            np.float64(0.0)
            >>> plt.close(fig)

            ```

    See Also:
        HAZE_COLORMAPS: Ready-made colormaps designed for this function.
        swatch_legend: A matching two-stop legend for the same data.
    """
    data = np.asarray(data, dtype=float)
    if data.ndim != 2:
        raise ValueError(f"data must be 2-dimensional, got shape {data.shape}")

    rgba = alpha_rgba(data, cmap, norm, alpha_norm, constant_alpha)
    return ax.imshow(rgba, **imshow_kwargs)

cleopatra.styling.colors.alpha_scaled_mesh(ax, x, y, data, cmap, *, norm=None, alpha_norm=None, constant_alpha=None, **pcolormesh_kwargs) #

Draw data on a curvilinear (x, y) mesh with per-cell opacity.

The pcolormesh counterpart to alpha_scaled_image. Use this instead of alpha_scaled_image whenever the grid is not a plain rectangle in axes coordinates -- e.g. data reprojected onto an orthographic globe by cleopatra.basemap.projection.orthographic_grid, or any other curvilinear (x, y) grid. Builds the same value-modulated-alpha RGBA colouring as alpha_scaled_image, then paints it onto the mesh via set_facecolor: pcolormesh's own cmap/norm/alpha machinery is bypassed because its alpha argument is a single scalar and cannot vary per cell.

Parameters:

Name Type Description Default
ax Axes

Axes to draw on.

required
x ndarray

2D array of cell x-coordinates, in Axes.pcolormesh's (X, Y, C) convention (either one larger than data per axis for exact cell edges, or the same shape with shading="auto"/"nearest").

required
y ndarray

2D array of cell y-coordinates, same convention as x.

required
data ndarray

2D array of values, one per mesh cell.

required
cmap str | Colormap

Colormap name or object, e.g. HAZE_COLORMAPS["dust"].

required
norm Normalize | None

Normalization mapping data to colour. Defaults to Normalize(vmin, vmax) over the finite range of data.

None
alpha_norm Normalize | None

Normalization mapping data to opacity. Defaults to norm.

None
constant_alpha float | None

If given, paint every finite cell at this fixed opacity (clipped to [0, 1]) and ignore alpha_norm -- e.g. 1.0 for a plain opaque field. Non-finite (NaN) cells stay transparent.

None
**pcolormesh_kwargs Any

Forwarded to ax.pcolormesh. shading defaults to "auto" if not given.

{}

Returns:

Name Type Description
QuadMesh Any

The mesh artist added to ax.

Raises:

Type Description
ValueError

If data is not 2-dimensional.

Examples:

  • A 2x2 curvilinear mesh with opacity fading toward zero:
    >>> import matplotlib
    >>> matplotlib.use("Agg")
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> from cleopatra.styling.colors import alpha_scaled_mesh
    >>> fig, ax = plt.subplots()
    >>> x, y = np.meshgrid(np.arange(3), np.arange(3))
    >>> data = np.array([[0.0, 1.0], [0.5, 1.0]])
    >>> mesh = alpha_scaled_mesh(ax, x, y, data, "viridis", shading="flat")
    >>> alpha = mesh.get_facecolor()[:, 3]
    >>> alpha[0]  # first cell, value 0.0 -> transparent
    np.float64(0.0)
    >>> alpha[1]  # second cell, value 1.0 -> opaque
    np.float64(1.0)
    >>> plt.close(fig)
    
See Also

alpha_scaled_image: The regular-grid counterpart (uses imshow). cleopatra.basemap.projection.orthographic_grid: Produces the (x, y, data) triple this function is designed to render.

Source code in src/cleopatra/styling/colors.py
def alpha_scaled_mesh(
    ax: Axes,
    x: np.ndarray,
    y: np.ndarray,
    data: np.ndarray,
    cmap: str | Colormap,
    *,
    norm: mcolors.Normalize | None = None,
    alpha_norm: mcolors.Normalize | None = None,
    constant_alpha: float | None = None,
    **pcolormesh_kwargs: Any,
) -> Any:
    """Draw `data` on a curvilinear `(x, y)` mesh with per-cell opacity.

    The `pcolormesh` counterpart to `alpha_scaled_image`. Use this instead of
    `alpha_scaled_image` whenever the grid is not a plain rectangle in axes
    coordinates -- e.g. data reprojected onto an orthographic globe by
    `cleopatra.basemap.projection.orthographic_grid`, or any other curvilinear
    `(x, y)` grid. Builds the same value-modulated-alpha RGBA colouring as
    `alpha_scaled_image`, then paints it onto the mesh via `set_facecolor`:
    `pcolormesh`'s own `cmap`/`norm`/`alpha` machinery is bypassed because its
    `alpha` argument is a single scalar and cannot vary per cell.

    Args:
        ax: Axes to draw on.
        x: 2D array of cell x-coordinates, in `Axes.pcolormesh`'s `(X, Y, C)`
            convention (either one larger than `data` per axis for exact
            cell edges, or the same shape with `shading="auto"`/`"nearest"`).
        y: 2D array of cell y-coordinates, same convention as `x`.
        data: 2D array of values, one per mesh cell.
        cmap: Colormap name or object, e.g. `HAZE_COLORMAPS["dust"]`.
        norm: Normalization mapping `data` to colour. Defaults to
            `Normalize(vmin, vmax)` over the finite range of `data`.
        alpha_norm: Normalization mapping `data` to opacity. Defaults to
            `norm`.
        constant_alpha: If given, paint every finite cell at this fixed opacity
            (clipped to `[0, 1]`) and ignore `alpha_norm` -- e.g. `1.0` for a
            plain opaque field. Non-finite (NaN) cells stay transparent.
        **pcolormesh_kwargs: Forwarded to `ax.pcolormesh`. `shading` defaults
            to `"auto"` if not given.

    Returns:
        QuadMesh: The mesh artist added to `ax`.

    Raises:
        ValueError: If `data` is not 2-dimensional.

    Examples:
        - A 2x2 curvilinear mesh with opacity fading toward zero:
            ```python
            >>> import matplotlib
            >>> matplotlib.use("Agg")
            >>> import numpy as np
            >>> import matplotlib.pyplot as plt
            >>> from cleopatra.styling.colors import alpha_scaled_mesh
            >>> fig, ax = plt.subplots()
            >>> x, y = np.meshgrid(np.arange(3), np.arange(3))
            >>> data = np.array([[0.0, 1.0], [0.5, 1.0]])
            >>> mesh = alpha_scaled_mesh(ax, x, y, data, "viridis", shading="flat")
            >>> alpha = mesh.get_facecolor()[:, 3]
            >>> alpha[0]  # first cell, value 0.0 -> transparent
            np.float64(0.0)
            >>> alpha[1]  # second cell, value 1.0 -> opaque
            np.float64(1.0)
            >>> plt.close(fig)

            ```

    See Also:
        alpha_scaled_image: The regular-grid counterpart (uses `imshow`).
        cleopatra.basemap.projection.orthographic_grid: Produces the `(x, y, data)`
            triple this function is designed to render.
    """
    data = np.asarray(data, dtype=float)
    if data.ndim != 2:
        raise ValueError(f"data must be 2-dimensional, got shape {data.shape}")

    pcolormesh_kwargs.setdefault("shading", "auto")
    rgba = alpha_rgba(data, cmap, norm, alpha_norm, constant_alpha)
    mesh = ax.pcolormesh(x, y, data, **pcolormesh_kwargs)
    mesh.set_array(None)
    mesh.set_facecolor(rgba.reshape(-1, 4))  # type: ignore[arg-type]
    return mesh

Examples#

Creating Color Objects#

from cleopatra.styling.colors import Colors

# Create a Colors object with a hex color
hex_color = Colors("#FF5733")

# Create a Colors object with an RGB color (normalized)
rgb_color = Colors((1.0, 0.34, 0.2))

# Create a Colors object with an RGB color (0-255)
rgb_255_color = Colors((255, 87, 51))

# Create a Colors object with a named color
named_color = Colors("red")

# Create a Colors object with a list of colors
color_list = Colors(["red", "green", "blue"])

Converting Between Color Formats#

# Convert to hex
hex_value = rgb_color.to_hex()
print(hex_value)  # "#FF5733"

# Convert to RGB (normalized)
rgb_value = hex_color.to_rgb(normalized=True)
print(rgb_value)  # (1.0, 0.34, 0.2)

# Convert to RGB (0-255)
rgb_255_value = hex_color.to_rgb(normalized=False)
print(rgb_255_value)  # (255, 87, 51)

Validating Color Values#

# Check if a hex color is valid
is_valid = hex_color.is_valid_hex()
print(is_valid)  # True

# Check if an RGB color is valid
is_valid = rgb_color.is_valid_rgb()
print(is_valid)  # True