Skip to content

Folium Legends

legends

Legends of value mappings on folium maps.

ContinuousColorscaleLegend

Bases: ContinuousLegendBase[SegmentedContinuousColorscale]

Legend for continuous color mappings.

Parameters:

Name Type Description Default
mapping ContinuousMappingType

Segmented continuous color scale.

required
**kwargs Any

Passed to ContinuousLegendBase and BaseLegend (title, position, n_ticks_per_segment, value_formatter, ...).

{}
Source code in src/mesqual/visualizations/folium_viz_system/legends/continuous_color.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class ContinuousColorscaleLegend(ContinuousLegendBase[SegmentedContinuousColorscale]):
    """Legend for continuous color mappings.

    Args:
        mapping: Segmented continuous color scale.
        **kwargs: Passed to `ContinuousLegendBase` and `BaseLegend` (title, position,
            n_ticks_per_segment, value_formatter, ...).
    """

    def specific_visual_styles(self) -> str:
        # no extra CSS beyond base
        return ''

    def create_segment_visual(self, start: float, end: float, colors: Any) -> str:
        if isinstance(colors, list):
            if len(colors) == 1:
                gradient = f'background: {colors[0]};'
            else:
                stops = [f'{color} {100 * i / (len(colors) - 1):.1f}%' for i, color in enumerate(colors)]
                gradient = f'background: linear-gradient(to right, {", ".join(stops)});'
        else:
            gradient = f'background: {colors};'
        return f'<div class="segment-visual" style="{gradient}"></div>'

ContinuousLineWidthMapLegend

Bases: ContinuousLegendBase[SegmentedContinuousLineWidthMapping]

Legend for continuous line width mappings.

Parameters:

Name Type Description Default
mapping SegmentedContinuousLineWidthMapping

Segmented continuous line width mapping.

required
line_color str

CSS color of the line shapes.

'#000000'
show_pixel_values bool

If True, show the width in px below the line shape of each segment.

False
**kwargs Any

Passed to ContinuousLegendBase and BaseLegend (title, position, value_formatter, ...).

{}
Source code in src/mesqual/visualizations/folium_viz_system/legends/continuous_line_width.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class ContinuousLineWidthMapLegend(ContinuousLegendBase[SegmentedContinuousLineWidthMapping]):
    """Legend for continuous line width mappings.

    Args:
        mapping: Segmented continuous line width mapping.
        line_color: CSS color of the line shapes.
        show_pixel_values: If True, show the width in px below the line shape of each segment.
        **kwargs: Passed to `ContinuousLegendBase` and `BaseLegend` (title, position,
            value_formatter, ...).
    """

    def __init__(
        self,
        mapping: SegmentedContinuousLineWidthMapping,
        line_color: str = '#000000',
        show_pixel_values: bool = False,
        **kwargs: Any,
    ):
        super().__init__(mapping, **kwargs)
        self.line_color = line_color
        self.show_pixel_values = show_pixel_values

    def specific_visual_styles(self) -> str:
        id_selector = f'#{self.get_name()}'
        return f"""
            {id_selector} .pixel-value {{
                font-size: {self.tick_font_size - 2}px;
                color: {self.tick_color};
                margin-bottom: 4px;
            }}
        """

    def create_segment_visual(self, start: float, end: float, width_data: float | list[float]) -> str:
        # trapezoid SVG
        if isinstance(width_data, list):
            w0, w1 = width_data[0], width_data[-1]
        else:
            w0 = w1 = width_data

        svg = f"""
            <svg width="100%" height="{self.segment_height}" preserveAspectRatio="none">
                <path d="
                    M0,{self.segment_height / 2 - w0 / 2}
                    L100,{self.segment_height / 2 - w1 / 2}
                    L100,{self.segment_height / 2 + w1 / 2}
                    L0,{self.segment_height / 2 + w0 / 2}
                    Z
                " fill="{self.line_color}" />
            </svg>
        """
        # pixel-value above ticks
        if self.show_pixel_values:
            label = f'{int(w0)}px' if w0 == w1 else f'{int(w0)}-{int(w1)}px'
            svg += f'<div class="pixel-value">{label}</div>'

        return svg

DiscreteColorLegend

Bases: DiscreteLegendBase[DiscreteColorMapping]

Legend for discrete color mappings.

Parameters:

Name Type Description Default
mapping DiscreteColorMapping

Discrete color mapping.

required
swatch_size int

Size of the color swatch in px.

20
**kwargs Any

Passed to DiscreteLegendBase (default_label, title, position, value_formatter, ...).

{}
Source code in src/mesqual/visualizations/folium_viz_system/legends/discrete_color.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class DiscreteColorLegend(DiscreteLegendBase[DiscreteColorMapping]):
    """Legend for discrete color mappings.

    Args:
        mapping: Discrete color mapping.
        swatch_size: Size of the color swatch in px.
        **kwargs: Passed to `DiscreteLegendBase` (default_label, title, position,
            value_formatter, ...).
    """

    def __init__(self, mapping: DiscreteColorMapping, swatch_size: int = 20, **kwargs: Any):
        super().__init__(mapping, **kwargs)
        self.swatch_size = swatch_size

    def specific_visual_styles(self) -> str:
        id_selector = f'#{self.get_name()}'
        return f"""
            {id_selector} .color-swatch {{
                width: {self.swatch_size}px;
                height: {self.swatch_size}px;
                border: 1px solid #ccc;
                border-radius: 2px;
            }}
        """

    def create_visual_element(self, color: str) -> str:
        return f'<div class="color-swatch" style="background-color: {color};"></div>'

DiscreteLineDashLegend

Bases: DiscreteLegendBase[DiscreteLineDashPatternMapping]

Legend for line dash pattern mappings.

Parameters:

Name Type Description Default
mapping DiscreteLineDashPatternMapping

Discrete line dash pattern mapping.

required
line_color str

CSS color of the lines.

'#000000'
line_width int

Line width in px.

2
**kwargs Any

Passed to DiscreteLegendBase (default_label, title, position, value_formatter, ...).

{}
Source code in src/mesqual/visualizations/folium_viz_system/legends/discrete_line_dash.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class DiscreteLineDashLegend(DiscreteLegendBase[DiscreteLineDashPatternMapping]):
    """Legend for line dash pattern mappings.

    Args:
        mapping: Discrete line dash pattern mapping.
        line_color: CSS color of the lines.
        line_width: Line width in px.
        **kwargs: Passed to `DiscreteLegendBase` (default_label, title, position,
            value_formatter, ...).
    """

    def __init__(
        self, mapping: DiscreteLineDashPatternMapping, line_color: str = '#000000', line_width: int = 2, **kwargs: Any
    ):
        super().__init__(mapping, **kwargs)
        self.line_color = line_color
        self.line_width = line_width

    def specific_visual_styles(self) -> str:
        id_selector = f'#{self.get_name()}'
        return f"""
            {id_selector} svg {{
                /* you can put shared SVG styling here if needed */
            }}
        """

    def create_visual_element(self, pattern: str) -> str:
        dash_array = f'stroke-dasharray="{pattern}"' if pattern else ''
        return f"""
            <svg width="{self.visual_column_width}" height="{self.line_width * 2}">
                <line x1="0" y1="{self.line_width}" x2="{self.visual_column_width}" y2="{self.line_width}"
                      stroke="{self.line_color}" stroke-width="{self.line_width}" {dash_array}/>
            </svg>
        """

DiscreteLineWidthLegend

Bases: DiscreteLegendBase[DiscreteLineWidthMapping]

Legend for discrete line width mappings.

Parameters:

Name Type Description Default
mapping DiscreteLineWidthMapping

Discrete line width mapping.

required
line_color str

CSS color of the lines.

'#000000'
show_pixel_values bool

If True, show the width in px behind each label.

False
**kwargs Any

Passed to DiscreteLegendBase (default_label, title, position, value_formatter, ...).

{}
Source code in src/mesqual/visualizations/folium_viz_system/legends/discrete_line_width.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class DiscreteLineWidthLegend(DiscreteLegendBase[DiscreteLineWidthMapping]):
    """Legend for discrete line width mappings.

    Args:
        mapping: Discrete line width mapping.
        line_color: CSS color of the lines.
        show_pixel_values: If True, show the width in px behind each label.
        **kwargs: Passed to `DiscreteLegendBase` (default_label, title, position,
            value_formatter, ...).
    """

    def __init__(
        self,
        mapping: DiscreteLineWidthMapping,
        line_color: str = '#000000',
        show_pixel_values: bool = False,
        **kwargs: Any,
    ):
        super().__init__(mapping, **kwargs)
        self.line_color = line_color
        self.show_pixel_values = show_pixel_values

    def specific_visual_styles(self) -> str:
        id_selector = f'#{self.get_name()}'
        return f"""
            {id_selector} .pixel-value {{
                font-size: {self.label_font_size - 2}px;
                color: {self.title_color};
                opacity: 0.7;
                margin-left: 5px;
            }}
        """

    def create_visual_element(self, width: float) -> str:
        height = max(10, width * 2)
        return f"""
            <svg width="{self.visual_column_width}" height="{height}">
                <line x1="0" y1="{height / 2}" x2="{self.visual_column_width}" y2="{height / 2}"
                      stroke="{self.line_color}" stroke-width="{width}"/>
            </svg>
        """

    def _item_label(self, key: Any, value: float) -> str:
        return self._with_pixel_value(self._format_label(key), value)

    def _default_item_label(self, value: float) -> str:
        return self._with_pixel_value(super()._default_item_label(value), value)

    def _with_pixel_value(self, label: str, width: float) -> str:
        if self.show_pixel_values:
            label += f'<span class="pixel-value">({width}px)</span>'
        return label

Base classes

base

Base class of all legends of value mappings.

BaseLegend

Bases: MacroElement, ABC, Generic[ValueMappingType]

Base class for all mapping legends with common functionality.

The title and the labels are text: the legend HTML-escapes them, so a value such as A<B shows as written.

Parameters:

Name Type Description Default
mapping ValueMappingType

Value mapping that the legend describes.

required
title str

Legend title, as text.

''
background_color str

CSS background color of the legend box.

'white'
title_color str

CSS color of the title.

'#333333'
title_font_size int

Title font size in px.

14
title_margin_bottom int

Space below the title in px.

8
font_family str

CSS font family.

'Arial, sans-serif'
width int

Width of the legend content in px.

200
padding int

Padding of the legend box in px.

10
border_radius int

Corner radius of the legend box in px.

5
position dict[str, int | float | str] | None

CSS position of the legend, for example {"bottom": 20, "right": 20}.

None
value_formatter Callable[[Any], str] | None

Function that returns the label text of every tick of a continuous legend and of every key of a discrete legend. Continuous legends pass the tick value as a float. Discrete legends pass the mapping key. The legend escapes the returned text. None keeps the default labels: integers and whole floats without decimals, other floats with up to 2 decimals, other values with str. The label of the default output of a discrete legend (default_label) is not formatted.

None

Examples:

Show values of a scale with the suffixes B and M:

>>> from mesqual.visualizations.folium_viz_system.legends import ContinuousColorscaleLegend
>>> from mesqual.visualizations.value_mapping_system import SegmentedContinuousColorscale
>>> def to_suffix(value: float) -> str:
...     if abs(value) >= 1e9:
...         return f"{value / 1e9:g}B"
...     if abs(value) >= 1e6:
...         return f"{value / 1e6:g}M"
...     return f"{value:g}"
>>> mapping = SegmentedContinuousColorscale(segments={(0, 2e9): ["#0000ff", "#ff0000"]})
>>> legend = ContinuousColorscaleLegend(mapping, value_formatter=to_suffix)
>>> "2B" in legend.render_content() and "2000000000" not in legend.render_content()
True
Source code in src/mesqual/visualizations/folium_viz_system/legends/base.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class BaseLegend(MacroElement, ABC, Generic[ValueMappingType]):
    """Base class for all mapping legends with common functionality.

    The title and the labels are text: the legend HTML-escapes them, so a value
    such as `A<B` shows as written.

    Args:
        mapping: Value mapping that the legend describes.
        title: Legend title, as text.
        background_color: CSS background color of the legend box.
        title_color: CSS color of the title.
        title_font_size: Title font size in px.
        title_margin_bottom: Space below the title in px.
        font_family: CSS font family.
        width: Width of the legend content in px.
        padding: Padding of the legend box in px.
        border_radius: Corner radius of the legend box in px.
        position: CSS position of the legend, for example `{"bottom": 20, "right": 20}`.
        value_formatter: Function that returns the label text of every tick of a
            continuous legend and of every key of a discrete legend. Continuous
            legends pass the tick value as a float. Discrete legends pass the
            mapping key. The legend escapes the returned text. `None` keeps the
            default labels: integers and whole floats without decimals, other
            floats with up to 2 decimals, other values with `str`. The label of
            the default output of a discrete legend (`default_label`) is not
            formatted.

    Examples:
        Show values of a scale with the suffixes `B` and `M`:

        >>> from mesqual.visualizations.folium_viz_system.legends import ContinuousColorscaleLegend
        >>> from mesqual.visualizations.value_mapping_system import SegmentedContinuousColorscale
        >>> def to_suffix(value: float) -> str:
        ...     if abs(value) >= 1e9:
        ...         return f"{value / 1e9:g}B"
        ...     if abs(value) >= 1e6:
        ...         return f"{value / 1e6:g}M"
        ...     return f"{value:g}"
        >>> mapping = SegmentedContinuousColorscale(segments={(0, 2e9): ["#0000ff", "#ff0000"]})
        >>> legend = ContinuousColorscaleLegend(mapping, value_formatter=to_suffix)
        >>> "2B" in legend.render_content() and "2000000000" not in legend.render_content()
        True
    """

    _base_template = Template("""
    {% macro header(this, kwargs) %}
        <style>
            #{{ this.get_name() }} {
                position: fixed;
                z-index: 1000;
                background: {{ this.background_color }};
                padding: {{ this.padding }}px;
                border-radius: {{ this.border_radius }}px;
                box-shadow: 0 0 5px rgba(0,0,0,0.2);
                font-family: {{ this.font_family }};
                {% for key, value in this.position.items() %}
                {{ key }}: {{ value }};
                {% endfor %}
            }
            #{{ this.get_name() }} .legend-title {
                margin-bottom: {{ this.title_margin_bottom }}px;
                font-size: {{ this.title_font_size }}px;
                font-weight: bold;
                color: {{ this.title_color }};
            }
            #{{ this.get_name() }} .legend-content {
                position: relative;
                width: {{ this.width }}px;
            }
            {{ this.additional_styles() }}
        </style>
    {% endmacro %}

    {% macro html(this, kwargs) %}
        <div id="{{ this.get_name() }}">
            {% if this.title %}
            <div class="legend-title">{{ this.title|e }}</div>
            {% endif %}
            <div class="legend-content">
                {{ this.render_content() }}
            </div>
        </div>
    {% endmacro %}
    """)

    def __init__(
        self,
        mapping: ValueMappingType,
        title: str = '',
        background_color: str = 'white',
        title_color: str = '#333333',
        title_font_size: int = 14,
        title_margin_bottom: int = 8,
        font_family: str = 'Arial, sans-serif',
        width: int = 200,
        padding: int = 10,
        border_radius: int = 5,
        position: dict[str, int | float | str] | None = None,
        value_formatter: Callable[[Any], str] | None = None,
    ):
        super().__init__()
        self._name = f'{self.__class__.__name__}_{id(self)}'
        self.mapping = mapping
        self.title = title
        self.background_color = background_color
        self.title_color = title_color
        self.title_font_size = title_font_size
        self.title_margin_bottom = title_margin_bottom
        self.font_family = font_family
        self.width = width
        self.padding = padding
        self.border_radius = border_radius
        self.position = self._process_position(position or {'bottom': '20px', 'right': '20px'})

        self.value_formatter = value_formatter

        self._template = self._base_template

    def __call__(self, value) -> Any:
        return self.mapping(value)

    def _process_position(self, position: dict[str, int | float | str]) -> dict[str, str]:
        return {k: f'{v}px' if isinstance(v, (int, float)) else str(v) for k, v in position.items()}

    @abstractmethod
    def additional_styles(self) -> str:
        """Return additional CSS styles specific to this legend type"""
        pass

    @abstractmethod
    def render_content(self) -> str:
        """Return the HTML content for the legend"""
        pass

    def _format_value(self, value: float | int | str) -> str:
        """Format a value for display"""
        if isinstance(value, (int, float)):
            if isinstance(value, float) and value % 1 == 0:
                return f'{int(value)}'
            return f'{value:.2f}'.rstrip('0').rstrip('.')
        return str(value)

    def _format_label(self, value: float | int | str) -> str:
        """Return the escaped label of a tick or key, using `value_formatter` if set."""
        formatter = self.value_formatter or self._format_value
        return escape(str(formatter(value)))
additional_styles abstractmethod
additional_styles() -> str

Return additional CSS styles specific to this legend type

Source code in src/mesqual/visualizations/folium_viz_system/legends/base.py
136
137
138
139
@abstractmethod
def additional_styles(self) -> str:
    """Return additional CSS styles specific to this legend type"""
    pass
render_content abstractmethod
render_content() -> str

Return the HTML content for the legend

Source code in src/mesqual/visualizations/folium_viz_system/legends/base.py
141
142
143
144
@abstractmethod
def render_content(self) -> str:
    """Return the HTML content for the legend"""
    pass

base_continuous

Base class of legends for continuous value mappings.

ContinuousLegendBase

Bases: Generic[ContinuousMappingType], BaseLegend[ContinuousMappingType]

Base class for continuous mapping legends with column-based segments.

Parameters:

Name Type Description Default
mapping ContinuousMappingType

Continuous value mapping that the legend describes.

required
segment_spacing int

Space between segments in px.

0
tick_font_size int

Tick label font size in px.

12
tick_color str | None

CSS color of the tick labels. Default is the title color.

None
n_ticks_per_segment int

Number of ticks per segment.

2
segment_height int

Height of the segment visual in px.

30
merge_adjacent_ticks bool

If True, the shared boundary of two segments gets one tick.

True
**kwargs Any

Passed to BaseLegend (title, position, value_formatter, ...).

{}
Source code in src/mesqual/visualizations/folium_viz_system/legends/base_continuous.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
class ContinuousLegendBase(Generic[ContinuousMappingType], BaseLegend[ContinuousMappingType]):
    """Base class for continuous mapping legends with column-based segments.

    Args:
        mapping: Continuous value mapping that the legend describes.
        segment_spacing: Space between segments in px.
        tick_font_size: Tick label font size in px.
        tick_color: CSS color of the tick labels. Default is the title color.
        n_ticks_per_segment: Number of ticks per segment.
        segment_height: Height of the segment visual in px.
        merge_adjacent_ticks: If True, the shared boundary of two segments gets one tick.
        **kwargs: Passed to `BaseLegend` (title, position, value_formatter, ...).
    """

    def __init__(
        self,
        mapping: ContinuousMappingType,
        segment_spacing: int = 0,
        tick_font_size: int = 12,
        tick_color: str | None = None,
        n_ticks_per_segment: int = 2,
        segment_height: int = 30,
        merge_adjacent_ticks: bool = True,
        **kwargs: Any,
    ):
        super().__init__(mapping, **kwargs)
        self.segment_spacing = segment_spacing
        self.tick_font_size = tick_font_size
        self.tick_color = tick_color or self.title_color
        self.n_ticks_per_segment = n_ticks_per_segment
        self.segment_height = segment_height
        self.merge_adjacent_ticks = merge_adjacent_ticks

    def additional_styles(self) -> str:
        """Return the CSS of the segment columns and ticks, followed by `specific_visual_styles()`."""
        id_selector = f'#{self.get_name()}'
        return f"""
            {id_selector} .segments-container {{
                display: flex;
                align-items: flex-start;
                gap: {self.segment_spacing}px;
            }}
            {id_selector} .segment-column {{
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: center;
            }}
            {id_selector} .segment-visual {{
                width: 100%;
                height: {self.segment_height}px;
                margin-bottom: 4px;
            }}
            {id_selector} .ticks-container {{
                position: relative;
                width: 100%;
                height: 20px;
                margin-top: 2px;
            }}
            {id_selector} .tick {{
                position: absolute;
                transform: translateX(-50%);
                font-size: {self.tick_font_size}px;
                color: {self.tick_color};
                white-space: nowrap;
            }}
            {self.specific_visual_styles()}
        """

    def render_content(self) -> str:
        """Return the HTML of the segments, sorted by their bounds.

        Each segment has the visual of `create_segment_visual` and
        `n_ticks_per_segment` ticks, spaced evenly from its start to its end.
        With `merge_adjacent_ticks`, each segment after the first leaves out
        its first tick.
        """
        segments_html: list[str] = []
        sorted_segments = sorted(self.mapping.segments.items())

        for idx, ((start, end), values) in enumerate(sorted_segments):
            # 1) visual
            visual_html = self.create_segment_visual(start, end, values)

            # 2) ticks for this segment
            raw_ticks = list(np.linspace(start, end, self.n_ticks_per_segment))
            if self.merge_adjacent_ticks and idx > 0:
                raw_ticks = raw_ticks[1:]

            # 3) build tick divs with conditional transform
            tick_divs: list[str] = []
            span = end - start
            for i, t in enumerate(raw_ticks):
                # compute percent along the box [0,100]
                pct = 0.0 if span == 0 else (t - start) / span * 100

                # choose transform so start/end snap to edges
                if not self.merge_adjacent_ticks:
                    if i == 0:
                        transform = 'translateX(0)'  # pin left edge
                    elif i == len(raw_ticks) - 1:
                        transform = 'translateX(-100%)'  # pin right edge
                    else:
                        transform = 'translateX(-50%)'  # center
                else:
                    # on merge, always center
                    transform = 'translateX(-50%)'

                tick_divs.append(
                    f'<div class="tick" style="left:{pct:.2f}%; transform:{transform};">'
                    f'{self._format_label(float(t))}</div>'
                )

            ticks_html = f'<div class="ticks-container">{"".join(tick_divs)}</div>'

            # 4) assemble segment column
            segments_html.append(f'<div class="segment-column">{visual_html}{ticks_html}</div>')

        return f'<div class="segments-container">{"".join(segments_html)}</div>'

    @abstractmethod
    def specific_visual_styles(self) -> str:
        """Return CSS styles specific to the visual representation"""
        pass

    @abstractmethod
    def create_segment_visual(self, start: float, end: float, values: any) -> str:
        """Create the visual representation for a segment"""
        pass
additional_styles
additional_styles() -> str

Return the CSS of the segment columns and ticks, followed by specific_visual_styles().

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_continuous.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def additional_styles(self) -> str:
    """Return the CSS of the segment columns and ticks, followed by `specific_visual_styles()`."""
    id_selector = f'#{self.get_name()}'
    return f"""
        {id_selector} .segments-container {{
            display: flex;
            align-items: flex-start;
            gap: {self.segment_spacing}px;
        }}
        {id_selector} .segment-column {{
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
        }}
        {id_selector} .segment-visual {{
            width: 100%;
            height: {self.segment_height}px;
            margin-bottom: 4px;
        }}
        {id_selector} .ticks-container {{
            position: relative;
            width: 100%;
            height: 20px;
            margin-top: 2px;
        }}
        {id_selector} .tick {{
            position: absolute;
            transform: translateX(-50%);
            font-size: {self.tick_font_size}px;
            color: {self.tick_color};
            white-space: nowrap;
        }}
        {self.specific_visual_styles()}
    """
render_content
render_content() -> str

Return the HTML of the segments, sorted by their bounds.

Each segment has the visual of create_segment_visual and n_ticks_per_segment ticks, spaced evenly from its start to its end. With merge_adjacent_ticks, each segment after the first leaves out its first tick.

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_continuous.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def render_content(self) -> str:
    """Return the HTML of the segments, sorted by their bounds.

    Each segment has the visual of `create_segment_visual` and
    `n_ticks_per_segment` ticks, spaced evenly from its start to its end.
    With `merge_adjacent_ticks`, each segment after the first leaves out
    its first tick.
    """
    segments_html: list[str] = []
    sorted_segments = sorted(self.mapping.segments.items())

    for idx, ((start, end), values) in enumerate(sorted_segments):
        # 1) visual
        visual_html = self.create_segment_visual(start, end, values)

        # 2) ticks for this segment
        raw_ticks = list(np.linspace(start, end, self.n_ticks_per_segment))
        if self.merge_adjacent_ticks and idx > 0:
            raw_ticks = raw_ticks[1:]

        # 3) build tick divs with conditional transform
        tick_divs: list[str] = []
        span = end - start
        for i, t in enumerate(raw_ticks):
            # compute percent along the box [0,100]
            pct = 0.0 if span == 0 else (t - start) / span * 100

            # choose transform so start/end snap to edges
            if not self.merge_adjacent_ticks:
                if i == 0:
                    transform = 'translateX(0)'  # pin left edge
                elif i == len(raw_ticks) - 1:
                    transform = 'translateX(-100%)'  # pin right edge
                else:
                    transform = 'translateX(-50%)'  # center
            else:
                # on merge, always center
                transform = 'translateX(-50%)'

            tick_divs.append(
                f'<div class="tick" style="left:{pct:.2f}%; transform:{transform};">'
                f'{self._format_label(float(t))}</div>'
            )

        ticks_html = f'<div class="ticks-container">{"".join(tick_divs)}</div>'

        # 4) assemble segment column
        segments_html.append(f'<div class="segment-column">{visual_html}{ticks_html}</div>')

    return f'<div class="segments-container">{"".join(segments_html)}</div>'
specific_visual_styles abstractmethod
specific_visual_styles() -> str

Return CSS styles specific to the visual representation

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_continuous.py
132
133
134
135
@abstractmethod
def specific_visual_styles(self) -> str:
    """Return CSS styles specific to the visual representation"""
    pass
create_segment_visual abstractmethod
create_segment_visual(start: float, end: float, values: any) -> str

Create the visual representation for a segment

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_continuous.py
137
138
139
140
@abstractmethod
def create_segment_visual(self, start: float, end: float, values: any) -> str:
    """Create the visual representation for a segment"""
    pass

base_discrete

Base class of legends for discrete value mappings.

DiscreteLegendBase

Bases: BaseLegend[DiscreteMappingType], Generic[DiscreteMappingType]

Base class for discrete mapping legends with two-column layout.

The legend has one row per entry of mapping.mapping, in its order, read when the map renders. A last row with the label default_label shows default_output when mapping.default_used is True.

Parameters:

Name Type Description Default
mapping DiscreteMappingType

Discrete value mapping that the legend describes.

required
visual_column_width int

Width of the visual column in px.

60
column_spacing int

Space between the visual and the label column in px.

10
row_spacing int

Space between rows in px.

8
label_font_size int

Label font size in px.

12
default_label str

Label of the row of default_output, as text. The legend escapes it and does not pass it to value_formatter.

'Other'
**kwargs Any

Passed to BaseLegend (title, position, value_formatter, ...).

{}

Examples:

The default row appears after the mapping has used default_output:

>>> from mesqual.visualizations.folium_viz_system.legends import DiscreteColorLegend
>>> from mesqual.visualizations.value_mapping_system import DiscreteColorMapping
>>> colors = DiscreteColorMapping(mapping={'wind': '#1f77b4'}, default_output='#cccccc')
>>> colors('coal')
'#cccccc'
>>> legend = DiscreteColorLegend(colors, title='Technology', default_label='Not mapped')
>>> 'Not mapped' in legend.render_content()
True
Source code in src/mesqual/visualizations/folium_viz_system/legends/base_discrete.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
class DiscreteLegendBase(BaseLegend[DiscreteMappingType], Generic[DiscreteMappingType]):
    """Base class for discrete mapping legends with two-column layout.

    The legend has one row per entry of `mapping.mapping`, in its order, read
    when the map renders. A last row with the label `default_label` shows
    `default_output` when `mapping.default_used` is True.

    Args:
        mapping: Discrete value mapping that the legend describes.
        visual_column_width: Width of the visual column in px.
        column_spacing: Space between the visual and the label column in px.
        row_spacing: Space between rows in px.
        label_font_size: Label font size in px.
        default_label: Label of the row of `default_output`, as text. The
            legend escapes it and does not pass it to `value_formatter`.
        **kwargs: Passed to `BaseLegend` (title, position, value_formatter, ...).

    Examples:
        The default row appears after the mapping has used `default_output`:

        >>> from mesqual.visualizations.folium_viz_system.legends import DiscreteColorLegend
        >>> from mesqual.visualizations.value_mapping_system import DiscreteColorMapping
        >>> colors = DiscreteColorMapping(mapping={'wind': '#1f77b4'}, default_output='#cccccc')
        >>> colors('coal')
        '#cccccc'
        >>> legend = DiscreteColorLegend(colors, title='Technology', default_label='Not mapped')
        >>> 'Not mapped' in legend.render_content()
        True
    """

    def __init__(
        self,
        mapping: DiscreteMappingType,
        visual_column_width: int = 60,
        column_spacing: int = 10,
        row_spacing: int = 8,
        label_font_size: int = 12,
        default_label: str = 'Other',
        **kwargs: Any,
    ):
        super().__init__(mapping, **kwargs)
        self.visual_column_width = visual_column_width
        self.column_spacing = column_spacing
        self.row_spacing = row_spacing
        self.label_font_size = label_font_size
        self.default_label = default_label

    def additional_styles(self) -> str:
        """Return the CSS of the rows and their two columns, followed by `specific_visual_styles()`."""
        id_selector = f'#{self.get_name()}'
        return f"""
            {id_selector} .discrete-item {{
                display: flex;
                align-items: center;
                margin-bottom: {self.row_spacing}px;
            }}
            {id_selector} .visual-column {{
                width: {self.visual_column_width}px;
                margin-right: {self.column_spacing}px;
                display: flex;
                align-items: center;
                justify-content: center;
            }}
            {id_selector} .label-column {{
                flex: 1;
                font-size: {self.label_font_size}px;
                color: {self.title_color};
            }}
            {self.specific_visual_styles()}
        """

    @abstractmethod
    def specific_visual_styles(self) -> str:
        """Return CSS styles specific to the visual representation"""
        pass

    @abstractmethod
    def create_visual_element(self, value: any) -> str:
        """Create the visual representation for a given value"""
        pass

    def _item_label(self, key: Any, value: Any) -> str:
        """Return the label of a mapped item."""
        return self._format_label(key)

    def _default_item_label(self, value: Any) -> str:
        """Return the escaped `default_label`, the label of the default output."""
        return escape(str(self.default_label))

    def _render_item(self, visual: str, label: str) -> str:
        return f"""
                <div class="discrete-item">
                    <div class="visual-column">{visual}</div>
                    <div class="label-column">{label}</div>
                </div>
            """

    def render_content(self) -> str:
        """Return the HTML of the rows.

        One row per entry of `mapping.mapping`, then the row of
        `default_output` if `mapping.default_used` is True and
        `default_output` is not None.
        """
        items = [
            self._render_item(self.create_visual_element(value), self._item_label(key, value))
            for key, value in self.mapping.mapping.items()
        ]
        default = self.mapping.default_output
        if self.mapping.default_used and default is not None:
            items.append(self._render_item(self.create_visual_element(default), self._default_item_label(default)))
        return ''.join(items)
additional_styles
additional_styles() -> str

Return the CSS of the rows and their two columns, followed by specific_visual_styles().

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_discrete.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def additional_styles(self) -> str:
    """Return the CSS of the rows and their two columns, followed by `specific_visual_styles()`."""
    id_selector = f'#{self.get_name()}'
    return f"""
        {id_selector} .discrete-item {{
            display: flex;
            align-items: center;
            margin-bottom: {self.row_spacing}px;
        }}
        {id_selector} .visual-column {{
            width: {self.visual_column_width}px;
            margin-right: {self.column_spacing}px;
            display: flex;
            align-items: center;
            justify-content: center;
        }}
        {id_selector} .label-column {{
            flex: 1;
            font-size: {self.label_font_size}px;
            color: {self.title_color};
        }}
        {self.specific_visual_styles()}
    """
specific_visual_styles abstractmethod
specific_visual_styles() -> str

Return CSS styles specific to the visual representation

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_discrete.py
82
83
84
85
@abstractmethod
def specific_visual_styles(self) -> str:
    """Return CSS styles specific to the visual representation"""
    pass
create_visual_element abstractmethod
create_visual_element(value: any) -> str

Create the visual representation for a given value

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_discrete.py
87
88
89
90
@abstractmethod
def create_visual_element(self, value: any) -> str:
    """Create the visual representation for a given value"""
    pass
render_content
render_content() -> str

Return the HTML of the rows.

One row per entry of mapping.mapping, then the row of default_output if mapping.default_used is True and default_output is not None.

Source code in src/mesqual/visualizations/folium_viz_system/legends/base_discrete.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def render_content(self) -> str:
    """Return the HTML of the rows.

    One row per entry of `mapping.mapping`, then the row of
    `default_output` if `mapping.default_used` is True and
    `default_output` is not None.
    """
    items = [
        self._render_item(self.create_visual_element(value), self._item_label(key, value))
        for key, value in self.mapping.mapping.items()
    ]
    default = self.mapping.default_output
    if self.mapping.default_used and default is not None:
        items.append(self._render_item(self.create_visual_element(default), self._default_item_label(default)))
    return ''.join(items)