Skip to content

MESQUAL HTML Dashboard

HTMLDashboard

A dashboard builder for creating HTML reports with multiple visualizations.

This class provides a flexible way to combine Plotly figures, Folium maps, HTML tables, custom HTML content, and section dividers into a single HTML dashboard file. Elements are stored with unique names and can be ordered when saving the final dashboard.

Parameters:

Name Type Description Default
name str

The dashboard title. Defaults to 'HTML Dashboard'.

None
font_family str

CSS font family specification for the dashboard. Defaults to "Arial, sans-serif".

'Arial, sans-serif'

Attributes:

Name Type Description
name

The dashboard title.

content Dict[str, HTMLDashboardElement]

Dictionary mapping element names to HTMLDashboardElement objects.

font_family

The CSS font family specification.

Example:

>>> import plotly.express as px
>>> dashboard = HTMLDashboard(name="My Analysis")
>>> fig = px.scatter(px.data.iris(), x="sepal_width", y="sepal_length")
>>> dashboard.add_plotly_figure(fig, name="iris_scatter")
>>> dashboard.save("analysis.html")
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
 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
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
class HTMLDashboard:
    """A dashboard builder for creating HTML reports with multiple visualizations.

    This class provides a flexible way to combine Plotly figures, Folium maps,
    HTML tables, custom HTML content, and section dividers into a single HTML
    dashboard file. Elements are stored with unique names and can be ordered
    when saving the final dashboard.

    Args:
        name: The dashboard title. Defaults to 'HTML Dashboard'.
        font_family: CSS font family specification for the dashboard.
            Defaults to "Arial, sans-serif".

    Attributes:
        name: The dashboard title.
        content: Dictionary mapping element names to HTMLDashboardElement objects.
        font_family: The CSS font family specification.

    Example:

        >>> import plotly.express as px
        >>> dashboard = HTMLDashboard(name="My Analysis")
        >>> fig = px.scatter(px.data.iris(), x="sepal_width", y="sepal_length")
        >>> dashboard.add_plotly_figure(fig, name="iris_scatter")
        >>> dashboard.save("analysis.html")
    """
    def __init__(self, name: str = None, font_family: str = "Arial, sans-serif"):
        self.name = name if name else 'HTML Dashboard'
        self.content: Dict[str, HTMLDashboardElement] = dict()
        self.font_family = font_family

    def add_plotly_figure(self, fig: go.Figure, height: str = '100%', name: str = None):
        """Add a Plotly figure to the dashboard.

        Args:
            fig: The Plotly figure to add.
            height: CSS height specification for the figure. Defaults to '100%'.
            name: Unique identifier for the figure. If None, auto-generates.

        Example:

            >>> import plotly.express as px
            >>> fig = px.bar(x=["A", "B", "C"], y=[1, 3, 2])
            >>> dashboard.add_plotly_figure(fig, height="400px", name="my_bar_chart")
        """
        element = HTMLDashboardElement(fig, height, name)
        self.content[element.name] = element

    def add_html(self, html_string: str, name: str = None):
        """Add custom HTML content to the dashboard.

        Args:
            html_string: The HTML content to add.
            name: Unique identifier for the HTML content. If None, auto-generates.

        Example:

            >>> html = "<div><h2>Custom Section</h2><p>Some content here.</p></div>"
            >>> dashboard.add_html(html, name="custom_section")
        """
        element = HTMLDashboardElement(html_string, name=name)
        self.content[element.name] = element

    def add_folium_map(
            self,
            folium_map: 'folium.Map',
            name: str = None,
    ):
        """Add a Folium map to the dashboard.

        Args:
            folium_map: The Folium map object to add.
            name: Unique identifier for the map. If None, auto-generates
                as "folium_map_{index}".

        Returns:
            str: The name assigned to the map element.

        Example:

            >>> import folium
            >>> m = folium.Map(location=[45.5236, -122.6750], zoom_start=13)
            >>> map_name = dashboard.add_folium_map(m, name="portland_map")
        """
        map_html = folium_map._repr_html_()

        if name is None:
            name = f"folium_map_{len([k for k in self.content.keys() if 'folium_map' in k])}"

        wrapped_map_html = f'<div>{map_html}</div>'

        self.add_html(wrapped_map_html, name=name)

        return name

    def add_table(
            self,
            table: 'HTMLTable',
            name: str = None,
            include_dependencies: bool = True
    ) -> str:
        """Add an HTML table to the dashboard.

        Args:
            table: The HTMLTable object to add.
            name: Unique identifier for the table. If None, derives from table title
                or uses table_id.
            include_dependencies: Whether to include CSS/JS dependencies in the
                table HTML. Defaults to True.

        Returns:
            str: The name assigned to the table element.

        Raises:
            ValueError: If the table cannot be converted to HTML.

        Example:

            >>> from mesqual.visualizations.html_table import HTMLTable
            >>> import pandas as pd
            >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
            >>> table = HTMLTable(df, title="Sample Data")
            >>> table_name = dashboard.add_table(table, name="sample_table")
        """
        try:
            table_html = table.get_html(include_dependencies=include_dependencies)

            if name is None:
                name = f"table_{table.title.lower().replace(' ', '_')}" if table.title else table.table_id

            self.add_html(table_html, name=name)
            return name

        except Exception as e:
            raise ValueError(f"Failed to add table to dashboard: {str(e)}") from e

    def add_section_divider(
            self,
            title: str,
            subtitle: str = None,
            name: str = None,
            background_color: str = "#f9f9f9",
            title_color: str = "#333",
            subtitle_color: str = "#666",
            padding: str = "20px",
            margin: str = "20px 0",
            text_align: str = "center",
            title_font_size: str = "24px",
            subtitle_font_size: str = "16px",
            border_radius: str = "0px",
            border: str = "none",
            **kwargs
    ) -> str:
        """Add a styled section divider with title and optional subtitle.

        Creates a formatted section header that can be used to organize dashboard
        content into logical groups. Supports extensive CSS customization through
        parameters and keyword arguments.

        Args:
            title: The main section title.
            subtitle: Optional subtitle text.
            name: Unique identifier for the divider. If None, derives from title.
            background_color: CSS background color. Defaults to "#f9f9f9".
            title_color: CSS color for the title text. Defaults to "#333".
            subtitle_color: CSS color for the subtitle text. Defaults to "#666".
            padding: CSS padding specification. Defaults to "20px".
            margin: CSS margin specification. Defaults to "20px 0".
            text_align: CSS text alignment. Defaults to "center".
            title_font_size: CSS font size for title. Defaults to "24px".
            subtitle_font_size: CSS font size for subtitle. Defaults to "16px".
            border_radius: CSS border radius. Defaults to "0px".
            border: CSS border specification. Defaults to "none".
            **kwargs: Additional CSS properties. Underscores in keys are converted
                to camelCase (e.g., box_shadow becomes boxShadow).

        Returns:
            str: The name assigned to the section divider element.

        Example:

            >>> divider_name = dashboard.add_section_divider(
            ...     title="Data Analysis Results",
            ...     subtitle="Generated on 2024-01-01",
            ...     background_color="#e3f2fd",
            ...     border="1px solid #2196f3"
            ... )
        """
        base_style = f"background-color: {background_color}; padding: {padding}; margin: {margin}; text-align: {text_align}; border-radius: {border_radius}; border: {border};"

        for key, value in kwargs.items():
            css_key = ''.join(word.capitalize() if i > 0 else word for i, word in enumerate(key.split('_')))
            base_style += f" {css_key}: {value};"

        html = f'<div style="{base_style}">\n'
        html += f'    <h2 style="color: {title_color}; font-size: {title_font_size};">{title}</h2>\n'

        if subtitle:
            html += f'    <p style="color: {subtitle_color}; font-size: {subtitle_font_size};">{subtitle}</p>\n'

        html += '</div>'

        if name is None:
            name = f"section_{title.lower().replace(' ', '_')}"

        self.add_html(html, name=name)

        return name

    def save(self, save_to_path, content_order=None):
        """Save the dashboard as an HTML file.

        Generates a complete HTML document containing all dashboard elements.
        Automatically handles Plotly.js inclusion (only includes once for efficiency)
        and creates output directories as needed.

        Args:
            save_to_path: File path where the HTML dashboard will be saved.
            content_order: Optional list specifying the order of elements in the
                dashboard. If None, uses the order elements were added. Must
                contain only valid element names.

        Raises:
            KeyError: If content_order contains names not found in the dashboard.
            TypeError: If an element has an unexpected type (internal error).

        Example:

            >>> dashboard.save("my_dashboard.html")
            >>> # Custom ordering
            >>> dashboard.save("ordered_dashboard.html",
            ...               content_order=["intro_section", "chart1", "table1"])
        """
        if not os.path.exists(os.path.dirname(save_to_path)):
            os.makedirs(os.path.dirname(save_to_path))

        if content_order is None:
            content_order = list(self.content.keys())
        else:
            unrecognized = [k for k in content_order if k not in self.content.keys()]
            if unrecognized:
                raise KeyError(f'Unrecognized content names: {unrecognized}. Allowed: {self.content.keys()}')

        content = []
        plotly_js_included = False
        for key in content_order:
            v = self.content[key]
            if isinstance(v.element, go.Figure):
                html_text = v.element.to_html(
                    include_plotlyjs=True if not plotly_js_included else False,
                    full_html=False,
                    default_height=v.height
                )
                content.append(html_text)
                plotly_js_included = True
            elif isinstance(v.element, str):
                content.append(v.element)
            else:
                TypeError(f'Unexpected element type: {type(v.element)}')

        with open(save_to_path, 'w', encoding='utf-8') as dashboard:
            dashboard.write("<html><head>\n")
            dashboard.write("<meta charset='UTF-8'>\n")
            dashboard.write(f"<title>{self.name}</title>\n")
            dashboard.write(f"<style>\n  body, * {{ font-family: {self.font_family}; }}\n</style>\n")
            dashboard.write("</head><body>\n")

            for item in content:
                dashboard.write(item + "\n")

            dashboard.write("</body></html>\n")

    def show(self, width: str = "100%", height: str = "600"):
        """Display the dashboard inline in a Jupyter notebook.

        Creates a temporary HTML file and displays it using an IPython IFrame.
        This method is designed for use within Jupyter notebooks to provide
        inline dashboard previews.

        Args:
            width: CSS width specification for the iframe. Defaults to "100%".
            height: CSS height specification for the iframe. Defaults to "600".

        Note:
            This method requires IPython and is intended for Jupyter notebook use.
            The temporary file is created in the system temp directory.

        Example:

            >>> # In a Jupyter notebook cell
            >>> dashboard.show(width="100%", height="800px")
        """
        import tempfile
        from pathlib import Path
        from IPython.display import IFrame, display

        tmp_dir = Path(tempfile.mkdtemp())
        html_path = tmp_dir / "dashboard.html"
        self.save(html_path)
        display(IFrame(src=str(html_path.resolve()), width=width, height=height))

add_plotly_figure

add_plotly_figure(fig: Figure, height: str = '100%', name: str = None)

Add a Plotly figure to the dashboard.

Parameters:

Name Type Description Default
fig Figure

The Plotly figure to add.

required
height str

CSS height specification for the figure. Defaults to '100%'.

'100%'
name str

Unique identifier for the figure. If None, auto-generates.

None

Example:

>>> import plotly.express as px
>>> fig = px.bar(x=["A", "B", "C"], y=[1, 3, 2])
>>> dashboard.add_plotly_figure(fig, height="400px", name="my_bar_chart")
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def add_plotly_figure(self, fig: go.Figure, height: str = '100%', name: str = None):
    """Add a Plotly figure to the dashboard.

    Args:
        fig: The Plotly figure to add.
        height: CSS height specification for the figure. Defaults to '100%'.
        name: Unique identifier for the figure. If None, auto-generates.

    Example:

        >>> import plotly.express as px
        >>> fig = px.bar(x=["A", "B", "C"], y=[1, 3, 2])
        >>> dashboard.add_plotly_figure(fig, height="400px", name="my_bar_chart")
    """
    element = HTMLDashboardElement(fig, height, name)
    self.content[element.name] = element

add_html

add_html(html_string: str, name: str = None)

Add custom HTML content to the dashboard.

Parameters:

Name Type Description Default
html_string str

The HTML content to add.

required
name str

Unique identifier for the HTML content. If None, auto-generates.

None

Example:

>>> html = "<div><h2>Custom Section</h2><p>Some content here.</p></div>"
>>> dashboard.add_html(html, name="custom_section")
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def add_html(self, html_string: str, name: str = None):
    """Add custom HTML content to the dashboard.

    Args:
        html_string: The HTML content to add.
        name: Unique identifier for the HTML content. If None, auto-generates.

    Example:

        >>> html = "<div><h2>Custom Section</h2><p>Some content here.</p></div>"
        >>> dashboard.add_html(html, name="custom_section")
    """
    element = HTMLDashboardElement(html_string, name=name)
    self.content[element.name] = element

add_folium_map

add_folium_map(folium_map: Map, name: str = None)

Add a Folium map to the dashboard.

Parameters:

Name Type Description Default
folium_map Map

The Folium map object to add.

required
name str

Unique identifier for the map. If None, auto-generates as "folium_map_{index}".

None

Returns:

Name Type Description
str

The name assigned to the map element.

Example:

>>> import folium
>>> m = folium.Map(location=[45.5236, -122.6750], zoom_start=13)
>>> map_name = dashboard.add_folium_map(m, name="portland_map")
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
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
def add_folium_map(
        self,
        folium_map: 'folium.Map',
        name: str = None,
):
    """Add a Folium map to the dashboard.

    Args:
        folium_map: The Folium map object to add.
        name: Unique identifier for the map. If None, auto-generates
            as "folium_map_{index}".

    Returns:
        str: The name assigned to the map element.

    Example:

        >>> import folium
        >>> m = folium.Map(location=[45.5236, -122.6750], zoom_start=13)
        >>> map_name = dashboard.add_folium_map(m, name="portland_map")
    """
    map_html = folium_map._repr_html_()

    if name is None:
        name = f"folium_map_{len([k for k in self.content.keys() if 'folium_map' in k])}"

    wrapped_map_html = f'<div>{map_html}</div>'

    self.add_html(wrapped_map_html, name=name)

    return name

add_table

add_table(table: HTMLTable, name: str = None, include_dependencies: bool = True) -> str

Add an HTML table to the dashboard.

Parameters:

Name Type Description Default
table HTMLTable

The HTMLTable object to add.

required
name str

Unique identifier for the table. If None, derives from table title or uses table_id.

None
include_dependencies bool

Whether to include CSS/JS dependencies in the table HTML. Defaults to True.

True

Returns:

Name Type Description
str str

The name assigned to the table element.

Raises:

Type Description
ValueError

If the table cannot be converted to HTML.

Example:

>>> from mesqual.visualizations.html_table import HTMLTable
>>> import pandas as pd
>>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
>>> table = HTMLTable(df, title="Sample Data")
>>> table_name = dashboard.add_table(table, name="sample_table")
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
139
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
def add_table(
        self,
        table: 'HTMLTable',
        name: str = None,
        include_dependencies: bool = True
) -> str:
    """Add an HTML table to the dashboard.

    Args:
        table: The HTMLTable object to add.
        name: Unique identifier for the table. If None, derives from table title
            or uses table_id.
        include_dependencies: Whether to include CSS/JS dependencies in the
            table HTML. Defaults to True.

    Returns:
        str: The name assigned to the table element.

    Raises:
        ValueError: If the table cannot be converted to HTML.

    Example:

        >>> from mesqual.visualizations.html_table import HTMLTable
        >>> import pandas as pd
        >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
        >>> table = HTMLTable(df, title="Sample Data")
        >>> table_name = dashboard.add_table(table, name="sample_table")
    """
    try:
        table_html = table.get_html(include_dependencies=include_dependencies)

        if name is None:
            name = f"table_{table.title.lower().replace(' ', '_')}" if table.title else table.table_id

        self.add_html(table_html, name=name)
        return name

    except Exception as e:
        raise ValueError(f"Failed to add table to dashboard: {str(e)}") from e

add_section_divider

add_section_divider(title: str, subtitle: str = None, name: str = None, background_color: str = '#f9f9f9', title_color: str = '#333', subtitle_color: str = '#666', padding: str = '20px', margin: str = '20px 0', text_align: str = 'center', title_font_size: str = '24px', subtitle_font_size: str = '16px', border_radius: str = '0px', border: str = 'none', **kwargs) -> str

Add a styled section divider with title and optional subtitle.

Creates a formatted section header that can be used to organize dashboard content into logical groups. Supports extensive CSS customization through parameters and keyword arguments.

Parameters:

Name Type Description Default
title str

The main section title.

required
subtitle str

Optional subtitle text.

None
name str

Unique identifier for the divider. If None, derives from title.

None
background_color str

CSS background color. Defaults to "#f9f9f9".

'#f9f9f9'
title_color str

CSS color for the title text. Defaults to "#333".

'#333'
subtitle_color str

CSS color for the subtitle text. Defaults to "#666".

'#666'
padding str

CSS padding specification. Defaults to "20px".

'20px'
margin str

CSS margin specification. Defaults to "20px 0".

'20px 0'
text_align str

CSS text alignment. Defaults to "center".

'center'
title_font_size str

CSS font size for title. Defaults to "24px".

'24px'
subtitle_font_size str

CSS font size for subtitle. Defaults to "16px".

'16px'
border_radius str

CSS border radius. Defaults to "0px".

'0px'
border str

CSS border specification. Defaults to "none".

'none'
**kwargs

Additional CSS properties. Underscores in keys are converted to camelCase (e.g., box_shadow becomes boxShadow).

{}

Returns:

Name Type Description
str str

The name assigned to the section divider element.

Example:

>>> divider_name = dashboard.add_section_divider(
...     title="Data Analysis Results",
...     subtitle="Generated on 2024-01-01",
...     background_color="#e3f2fd",
...     border="1px solid #2196f3"
... )
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
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
def add_section_divider(
        self,
        title: str,
        subtitle: str = None,
        name: str = None,
        background_color: str = "#f9f9f9",
        title_color: str = "#333",
        subtitle_color: str = "#666",
        padding: str = "20px",
        margin: str = "20px 0",
        text_align: str = "center",
        title_font_size: str = "24px",
        subtitle_font_size: str = "16px",
        border_radius: str = "0px",
        border: str = "none",
        **kwargs
) -> str:
    """Add a styled section divider with title and optional subtitle.

    Creates a formatted section header that can be used to organize dashboard
    content into logical groups. Supports extensive CSS customization through
    parameters and keyword arguments.

    Args:
        title: The main section title.
        subtitle: Optional subtitle text.
        name: Unique identifier for the divider. If None, derives from title.
        background_color: CSS background color. Defaults to "#f9f9f9".
        title_color: CSS color for the title text. Defaults to "#333".
        subtitle_color: CSS color for the subtitle text. Defaults to "#666".
        padding: CSS padding specification. Defaults to "20px".
        margin: CSS margin specification. Defaults to "20px 0".
        text_align: CSS text alignment. Defaults to "center".
        title_font_size: CSS font size for title. Defaults to "24px".
        subtitle_font_size: CSS font size for subtitle. Defaults to "16px".
        border_radius: CSS border radius. Defaults to "0px".
        border: CSS border specification. Defaults to "none".
        **kwargs: Additional CSS properties. Underscores in keys are converted
            to camelCase (e.g., box_shadow becomes boxShadow).

    Returns:
        str: The name assigned to the section divider element.

    Example:

        >>> divider_name = dashboard.add_section_divider(
        ...     title="Data Analysis Results",
        ...     subtitle="Generated on 2024-01-01",
        ...     background_color="#e3f2fd",
        ...     border="1px solid #2196f3"
        ... )
    """
    base_style = f"background-color: {background_color}; padding: {padding}; margin: {margin}; text-align: {text_align}; border-radius: {border_radius}; border: {border};"

    for key, value in kwargs.items():
        css_key = ''.join(word.capitalize() if i > 0 else word for i, word in enumerate(key.split('_')))
        base_style += f" {css_key}: {value};"

    html = f'<div style="{base_style}">\n'
    html += f'    <h2 style="color: {title_color}; font-size: {title_font_size};">{title}</h2>\n'

    if subtitle:
        html += f'    <p style="color: {subtitle_color}; font-size: {subtitle_font_size};">{subtitle}</p>\n'

    html += '</div>'

    if name is None:
        name = f"section_{title.lower().replace(' ', '_')}"

    self.add_html(html, name=name)

    return name

save

save(save_to_path, content_order=None)

Save the dashboard as an HTML file.

Generates a complete HTML document containing all dashboard elements. Automatically handles Plotly.js inclusion (only includes once for efficiency) and creates output directories as needed.

Parameters:

Name Type Description Default
save_to_path

File path where the HTML dashboard will be saved.

required
content_order

Optional list specifying the order of elements in the dashboard. If None, uses the order elements were added. Must contain only valid element names.

None

Raises:

Type Description
KeyError

If content_order contains names not found in the dashboard.

TypeError

If an element has an unexpected type (internal error).

Example:

>>> dashboard.save("my_dashboard.html")
>>> # Custom ordering
>>> dashboard.save("ordered_dashboard.html",
...               content_order=["intro_section", "chart1", "table1"])
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
def save(self, save_to_path, content_order=None):
    """Save the dashboard as an HTML file.

    Generates a complete HTML document containing all dashboard elements.
    Automatically handles Plotly.js inclusion (only includes once for efficiency)
    and creates output directories as needed.

    Args:
        save_to_path: File path where the HTML dashboard will be saved.
        content_order: Optional list specifying the order of elements in the
            dashboard. If None, uses the order elements were added. Must
            contain only valid element names.

    Raises:
        KeyError: If content_order contains names not found in the dashboard.
        TypeError: If an element has an unexpected type (internal error).

    Example:

        >>> dashboard.save("my_dashboard.html")
        >>> # Custom ordering
        >>> dashboard.save("ordered_dashboard.html",
        ...               content_order=["intro_section", "chart1", "table1"])
    """
    if not os.path.exists(os.path.dirname(save_to_path)):
        os.makedirs(os.path.dirname(save_to_path))

    if content_order is None:
        content_order = list(self.content.keys())
    else:
        unrecognized = [k for k in content_order if k not in self.content.keys()]
        if unrecognized:
            raise KeyError(f'Unrecognized content names: {unrecognized}. Allowed: {self.content.keys()}')

    content = []
    plotly_js_included = False
    for key in content_order:
        v = self.content[key]
        if isinstance(v.element, go.Figure):
            html_text = v.element.to_html(
                include_plotlyjs=True if not plotly_js_included else False,
                full_html=False,
                default_height=v.height
            )
            content.append(html_text)
            plotly_js_included = True
        elif isinstance(v.element, str):
            content.append(v.element)
        else:
            TypeError(f'Unexpected element type: {type(v.element)}')

    with open(save_to_path, 'w', encoding='utf-8') as dashboard:
        dashboard.write("<html><head>\n")
        dashboard.write("<meta charset='UTF-8'>\n")
        dashboard.write(f"<title>{self.name}</title>\n")
        dashboard.write(f"<style>\n  body, * {{ font-family: {self.font_family}; }}\n</style>\n")
        dashboard.write("</head><body>\n")

        for item in content:
            dashboard.write(item + "\n")

        dashboard.write("</body></html>\n")

show

show(width: str = '100%', height: str = '600')

Display the dashboard inline in a Jupyter notebook.

Creates a temporary HTML file and displays it using an IPython IFrame. This method is designed for use within Jupyter notebooks to provide inline dashboard previews.

Parameters:

Name Type Description Default
width str

CSS width specification for the iframe. Defaults to "100%".

'100%'
height str

CSS height specification for the iframe. Defaults to "600".

'600'
Note

This method requires IPython and is intended for Jupyter notebook use. The temporary file is created in the system temp directory.

Example:

>>> # In a Jupyter notebook cell
>>> dashboard.show(width="100%", height="800px")
Source code in submodules/mesqual/mesqual/visualizations/html_dashboard.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
def show(self, width: str = "100%", height: str = "600"):
    """Display the dashboard inline in a Jupyter notebook.

    Creates a temporary HTML file and displays it using an IPython IFrame.
    This method is designed for use within Jupyter notebooks to provide
    inline dashboard previews.

    Args:
        width: CSS width specification for the iframe. Defaults to "100%".
        height: CSS height specification for the iframe. Defaults to "600".

    Note:
        This method requires IPython and is intended for Jupyter notebook use.
        The temporary file is created in the system temp directory.

    Example:

        >>> # In a Jupyter notebook cell
        >>> dashboard.show(width="100%", height="800px")
    """
    import tempfile
    from pathlib import Path
    from IPython.display import IFrame, display

    tmp_dir = Path(tempfile.mkdtemp())
    html_path = tmp_dir / "dashboard.html"
    self.save(html_path)
    display(IFrame(src=str(html_path.resolve()), width=width, height=height))