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']
>>> 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']
>>> 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 | |
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:
Get color values from a Colors object with mixed color formats:
__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):
-
Initialize with an RGB color (values between 0 and 255):
-
Initialize with a list of colors:
Source code in src/cleopatra/styling/colors.py
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 | |
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.

Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike
|
The path to the image file, as a |
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
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:
Source code in src/cleopatra/styling/colors.py
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):
-
Determine the type of an RGB color with values between 0-255:
-
Determine types of mixed color formats:
Source code in src/cleopatra/styling/colors.py
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 | |
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]
>>> rgb_colors = Colors([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
>>> rgb_colors.is_valid_hex()
[False, False, False]
>>> mixed = Colors(["#ff0000", (0, 255, 0), "not-a-color"])
>>> mixed.is_valid_hex()
[True, False, False]
Source code in src/cleopatra/styling/colors.py
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]
>>> hex_colors = Colors(["#ff0000", "#00ff00", "#0000ff"])
>>> hex_colors.is_valid_rgb()
[False, False, False]
>>> 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
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 = Colors(["#ff0000", "#00ff00", "#0000ff"])
>>> hex_colors.to_hex()
['#ff0000', '#00ff00', '#0000ff']
Source code in src/cleopatra/styling/colors.py
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):
-
Convert hex colors to standard RGB (0-255 range):
-
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
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 | |
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— readyLinearSegmentedColormapobjects ("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 withimshowwhere low values fade to transparent (NaN is always fully transparent).alpha_scaled_mesh— thepcolormesh/ curvilinear-grid counterpart, fororthographic_gridoutput.apply_data_style— draw one or more named layers with aDATA_STYLESpreset (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 |
required |
style
|
str
|
A name from |
'haze'
|
x
|
ndarray | None
|
Optional 2D curvilinear x-coordinates (see |
None
|
y
|
ndarray | None
|
Optional 2D curvilinear y-coordinates, paired with |
None
|
legend
|
bool
|
If |
True
|
legend_bounds
|
list[tuple[float, float, float, float]] | None
|
Explicit |
None
|
swatch_text_color
|
str
|
Colour of each swatch legend's title, by default
|
'white'
|
swatch_value_color
|
str | None
|
Optional colour for the swatch endpoint values, by
default |
None
|
swatch_box
|
bool | str | dict | None
|
Optional opaque backing panel behind each swatch legend
( |
None
|
**render_kwargs
|
Any
|
Forwarded to every |
{}
|
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 |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
ValueError
|
If exactly one of |
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/yrenders on a curvilinear mesh instead ofimshow:>>> 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
KeyErrorbefore 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 | |
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. |
required |
norm
|
Normalize | None
|
Normalization mapping |
None
|
alpha_norm
|
Normalize | None
|
Normalization mapping |
None
|
constant_alpha
|
float | None
|
If given, draw every finite cell at this fixed opacity
(clipped to |
None
|
**imshow_kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
AxesImage |
AxesImage
|
The image artist added to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | |
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 |
required |
y
|
ndarray
|
2D array of cell y-coordinates, same convention as |
required |
data
|
ndarray
|
2D array of values, one per mesh cell. |
required |
cmap
|
str | Colormap
|
Colormap name or object, e.g. |
required |
norm
|
Normalize | None
|
Normalization mapping |
None
|
alpha_norm
|
Normalize | None
|
Normalization mapping |
None
|
constant_alpha
|
float | None
|
If given, paint every finite cell at this fixed opacity
(clipped to |
None
|
**pcolormesh_kwargs
|
Any
|
Forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
QuadMesh |
Any
|
The mesh artist added to |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 | |
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)