Skip to content

MESQUAL Folium Text-Overlay Visualization System

viz_text_overlay

ResolvedTextOverlayFeature dataclass

Bases: ResolvedFeature

Resolved visual properties for text overlay elements.

Container for all computed styling properties of text overlay visualizations, including font styling, positioning, colors, and shadow effects. Used by TextOverlayGenerator to create folium markers with styled text content.

Source code in submodules/mesqual/mesqual/visualizations/folium_viz_system/viz_text_overlay.py
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
@dataclass
class ResolvedTextOverlayFeature(ResolvedFeature):
    """
    Resolved visual properties for text overlay elements.

    Container for all computed styling properties of text overlay visualizations,
    including font styling, positioning, colors, and shadow effects.
    Used by TextOverlayGenerator to create folium markers with styled text content.
    """

    @property
    def location(self) -> Point:
        return self.get('location')

    @property
    def offset(self) -> tuple[float, float]:
        return self.get('offset')

    @property
    def azimuth_angle(self) -> float:
        return self.get('azimuth_angle')

    @property
    def text_color(self) -> str:
        return self.get('text_color')

    @property
    def font_size(self) -> str:
        return self.get('font_size')

    @property
    def font_weight(self) -> str:
        return self.get('font_weight')

    @property
    def background_color(self) -> str:
        return self.get('background_color')

    @property
    def shadow_size(self) -> float:
        return self.get('shadow_size')

    @property
    def shadow_color(self) -> str:
        return self.get('shadow_color')

TextOverlayFeatureResolver

Bases: FeatureResolver[ResolvedTextOverlayFeature]

Resolves visual properties for text overlay elements.

Specialized feature resolver for text overlay visualizations that handles text content, font styling, positioning, and visual effects. Commonly used for adding data labels, value displays, or annotations to map elements.

Parameters:

Name Type Description Default
text_color PropertyMapper | str

Text color (static value or PropertyMapper)

'#3A3A3A'
font_size PropertyMapper | str

Font size with units like '10pt' (static value or PropertyMapper)

'10pt'
font_weight PropertyMapper | str

Font weight like 'bold', 'normal' (static value or PropertyMapper)

'bold'
background_color PropertyMapper | str

Background color for text (static value or PropertyMapper)

None
shadow_size PropertyMapper | str

Text shadow size like '0.5px' (static value or PropertyMapper)

'0.5px'
shadow_color PropertyMapper | str

Text shadow color (static value or PropertyMapper)

'#F2F2F2'
text_print_content PropertyMapper | str | bool

Text content to display (True for auto-generated)

True
tooltip PropertyMapper | str | bool

Tooltip content (True for auto-generated, False for none)

True
popup PropertyMapper | Popup | bool

Popup content (True/False/PropertyMapper)

False
location PropertyMapper | Point

Point location (defaults to smart location detection)

None
**property_mappers PropertyMapper | Any

Additional custom property mappings

{}

Examples:

Basic value labels:

>>> resolver = TextOverlayFeatureResolver(
...     text_color='#000000',
...     font_size='12pt',
...     font_weight='bold'
... )

Data-driven text styling:

>>> resolver = TextOverlayFeatureResolver(
...     text_color=PropertyMapper.from_kpi_value(
...         lambda v: '#FF0000' if v > 100 else '#000000'
...     ),
...     font_size=PropertyMapper.from_kpi_value(
...         lambda v: f'{min(max(8 + v/50, 8), 20)}pt'
...     ),
...     text_print_content=PropertyMapper.from_kpi_value(
...         lambda v: f'{v:.0f} MW'
...     )
... )
Source code in submodules/mesqual/mesqual/visualizations/folium_viz_system/viz_text_overlay.py
 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
class TextOverlayFeatureResolver(FeatureResolver[ResolvedTextOverlayFeature]):
    """
    Resolves visual properties for text overlay elements.

    Specialized feature resolver for text overlay visualizations that handles text
    content, font styling, positioning, and visual effects. Commonly used for
    adding data labels, value displays, or annotations to map elements.

    Args:
        text_color: Text color (static value or PropertyMapper)
        font_size: Font size with units like '10pt' (static value or PropertyMapper)
        font_weight: Font weight like 'bold', 'normal' (static value or PropertyMapper)
        background_color: Background color for text (static value or PropertyMapper)
        shadow_size: Text shadow size like '0.5px' (static value or PropertyMapper)
        shadow_color: Text shadow color (static value or PropertyMapper)
        text_print_content: Text content to display (True for auto-generated)
        tooltip: Tooltip content (True for auto-generated, False for none)
        popup: Popup content (True/False/PropertyMapper)
        location: Point location (defaults to smart location detection)
        **property_mappers: Additional custom property mappings

    Examples:
        Basic value labels:
        >>> resolver = TextOverlayFeatureResolver(
        ...     text_color='#000000',
        ...     font_size='12pt',
        ...     font_weight='bold'
        ... )

        Data-driven text styling:
        >>> resolver = TextOverlayFeatureResolver(
        ...     text_color=PropertyMapper.from_kpi_value(
        ...         lambda v: '#FF0000' if v > 100 else '#000000'
        ...     ),
        ...     font_size=PropertyMapper.from_kpi_value(
        ...         lambda v: f'{min(max(8 + v/50, 8), 20)}pt'
        ...     ),
        ...     text_print_content=PropertyMapper.from_kpi_value(
        ...         lambda v: f'{v:.0f} MW'
        ...     )
        ... )
    """
    def __init__(
            self,
            text_color: PropertyMapper | str = '#3A3A3A',
            font_size: PropertyMapper | str = '10pt',
            font_weight: PropertyMapper | str = 'bold',
            background_color: PropertyMapper | str = None,
            shadow_size: PropertyMapper | str = '0.5px',
            shadow_color: PropertyMapper | str = '#F2F2F2',
            text_print_content: PropertyMapper | str | bool = True,
            tooltip: PropertyMapper | str | bool = True,
            popup: PropertyMapper | folium.Popup | bool = False,
            location: PropertyMapper | Point = None,
            offset: PropertyMapper | tuple[float, float] = (0, 0),
            azimuth_angle: PropertyMapper | float = 90,
            **property_mappers: PropertyMapper | Any,
    ):
        mappers = dict(
            text_color=text_color,
            font_size=font_size,
            font_weight=font_weight,
            background_color=background_color,
            shadow_size=shadow_size,
            shadow_color=shadow_color,
            text_print_content=text_print_content,
            tooltip=tooltip,
            popup=popup,
            location=self._explicit_or_fallback(location, self._default_location_mapper()),
            offset=offset,
            azimuth_angle=azimuth_angle,
            **property_mappers
        )
        super().__init__(feature_type=ResolvedTextOverlayFeature, **mappers)

TextOverlayGenerator

Bases: FoliumObjectGenerator[TextOverlayFeatureResolver]

Generates text overlays for map data items.

Creates folium Marker objects with styled HTML text content overlaid on the map. Handles text formatting, positioning, shadow effects, and responsive styling based on data values.

Commonly used for displaying: - KPI values directly on map elements (power flows, prices, etc.) - Data labels for areas, lines, or points - Dynamic text that changes based on underlying data - Status indicators or categorical labels

Examples:

Value display on bidding zones:

>>> from mesqual.units import Units
>>> text_gen = TextOverlayGenerator(
...     TextOverlayFeatureResolver(
...         text_print_content=PropertyMapper(
...             lambda di: Units.get_pretty_text_for_quantity(
...                 di.kpi.quantity, decimals=0, include_unit=False
...             )
...         ),
...         font_size='10pt',
...         font_weight='bold'
...     )
... )
>>> 
>>> fg = folium.FeatureGroup('Price Labels')
>>> text_gen.generate_objects_for_kpi_collection(price_kpis, fg)
>>> fg.add_to(map)

Combined with area visualization:

>>> area_gen = AreaGenerator(...)
>>> text_gen = TextOverlayGenerator(...)
>>> 
>>> area_gen.generate_objects_for_model_df(zones_df, feature_group)
>>> text_gen.generate_objects_for_model_df(zones_df, feature_group)
Source code in submodules/mesqual/mesqual/visualizations/folium_viz_system/viz_text_overlay.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
class TextOverlayGenerator(FoliumObjectGenerator[TextOverlayFeatureResolver]):
    """
    Generates text overlays for map data items.

    Creates folium Marker objects with styled HTML text content overlaid on
    the map. Handles text formatting, positioning, shadow effects, and
    responsive styling based on data values.

    Commonly used for displaying:
    - KPI values directly on map elements (power flows, prices, etc.)
    - Data labels for areas, lines, or points
    - Dynamic text that changes based on underlying data
    - Status indicators or categorical labels

    Examples:
        Value display on bidding zones:
        >>> from mesqual.units import Units
        >>> text_gen = TextOverlayGenerator(
        ...     TextOverlayFeatureResolver(
        ...         text_print_content=PropertyMapper(
        ...             lambda di: Units.get_pretty_text_for_quantity(
        ...                 di.kpi.quantity, decimals=0, include_unit=False
        ...             )
        ...         ),
        ...         font_size='10pt',
        ...         font_weight='bold'
        ...     )
        ... )
        >>> 
        >>> fg = folium.FeatureGroup('Price Labels')
        >>> text_gen.generate_objects_for_kpi_collection(price_kpis, fg)
        >>> fg.add_to(map)

        Combined with area visualization:
        >>> area_gen = AreaGenerator(...)
        >>> text_gen = TextOverlayGenerator(...)
        >>> 
        >>> area_gen.generate_objects_for_model_df(zones_df, feature_group)
        >>> text_gen.generate_objects_for_model_df(zones_df, feature_group)
    """
    """Generates text overlays for map data items."""

    def _feature_resolver_type(self) -> Type[TextOverlayFeatureResolver]:
        return TextOverlayFeatureResolver

    def generate(self, data_item: VisualizableDataItem, feature_group: folium.FeatureGroup) -> None:
        """
        Generate and add a folium Marker with styled text overlay.

        Args:
            data_item: Data item containing point location and text content
            feature_group: Folium feature group to add the text marker to
        """
        style = self.feature_resolver.resolve_feature(data_item)
        if not isinstance(style.location, Point):
            return

        if not style.text_print_content:
            return

        text_content = style.text_print_content
        text_color = style.text_color
        font_size = style.font_size
        font_weight = style.font_weight
        shadow_size = style.shadow_size
        shadow_color = style.shadow_color

        angle = float(style.azimuth_angle) - 90  # Folium counts clockwise from right-pointing direction; normal convention is CCW
        x_offset, y_offset = style.offset

        icon_html = f'''
            <div style="
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%) translate({x_offset}px, {-y_offset}px) rotate({angle}deg);
                text-align: center;
                font-size: {font_size};
                font-weight: {font_weight};
                color: {text_color};
                white-space: nowrap;
                text-shadow:
                   -{shadow_size} -{shadow_size} 0 {shadow_color},  
                    {shadow_size} -{shadow_size} 0 {shadow_color},
                   -{shadow_size}  {shadow_size} 0 {shadow_color},
                    {shadow_size}  {shadow_size} 0 {shadow_color};
            ">
                {text_content}
            </div>
        '''

        folium.Marker(
            location=(style.location.y, style.location.x),
            icon=folium.DivIcon(html=icon_html),
            tooltip=style.tooltip,
            popup=style.popup,
        ).add_to(feature_group)

    def _get_contrasting_color(self, surface_color: str) -> str:
        """Get contrasting text color for a surface color."""
        if self._is_dark(surface_color):
            return '#F2F2F2'
        return '#3A3A3A'

    def _get_shadow_color(self, text_color: str) -> str:
        """Get shadow color for text."""
        if text_color == '#F2F2F2':
            return '#3A3A3A'
        return '#F2F2F2'

    @staticmethod
    def _is_dark(color: str) -> bool:
        """Check if a color is dark."""
        if not color.startswith('#'):
            return False
        try:
            r, g, b = [int(color[i:i + 2], 16) for i in (1, 3, 5)]
            return (0.299 * r + 0.587 * g + 0.114 * b) < 160
        except (ValueError, IndexError):
            return False

generate

generate(data_item: VisualizableDataItem, feature_group: FeatureGroup) -> None

Generate and add a folium Marker with styled text overlay.

Parameters:

Name Type Description Default
data_item VisualizableDataItem

Data item containing point location and text content

required
feature_group FeatureGroup

Folium feature group to add the text marker to

required
Source code in submodules/mesqual/mesqual/visualizations/folium_viz_system/viz_text_overlay.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def generate(self, data_item: VisualizableDataItem, feature_group: folium.FeatureGroup) -> None:
    """
    Generate and add a folium Marker with styled text overlay.

    Args:
        data_item: Data item containing point location and text content
        feature_group: Folium feature group to add the text marker to
    """
    style = self.feature_resolver.resolve_feature(data_item)
    if not isinstance(style.location, Point):
        return

    if not style.text_print_content:
        return

    text_content = style.text_print_content
    text_color = style.text_color
    font_size = style.font_size
    font_weight = style.font_weight
    shadow_size = style.shadow_size
    shadow_color = style.shadow_color

    angle = float(style.azimuth_angle) - 90  # Folium counts clockwise from right-pointing direction; normal convention is CCW
    x_offset, y_offset = style.offset

    icon_html = f'''
        <div style="
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%) translate({x_offset}px, {-y_offset}px) rotate({angle}deg);
            text-align: center;
            font-size: {font_size};
            font-weight: {font_weight};
            color: {text_color};
            white-space: nowrap;
            text-shadow:
               -{shadow_size} -{shadow_size} 0 {shadow_color},  
                {shadow_size} -{shadow_size} 0 {shadow_color},
               -{shadow_size}  {shadow_size} 0 {shadow_color},
                {shadow_size}  {shadow_size} 0 {shadow_color};
        ">
            {text_content}
        </div>
    '''

    folium.Marker(
        location=(style.location.y, style.location.x),
        icon=folium.DivIcon(html=icon_html),
        tooltip=style.tooltip,
        popup=style.popup,
    ).add_to(feature_group)