Skip to content

Interactive Visualization

Interactive HTML-based network exploration.

Overview

The interactive_plot module provides Plotly-based interactive visualizations.

Features: - HTML output - Zoom and pan - Hover information - Click selection - Web embedding

Modules

pypopart.visualization.interactive_plot

Interactive network visualization using Plotly for PyPopART.

Provides Plotly-based interactive plotting for haplotype networks with hover information, zoom/pan, and clickable elements.

InteractiveNetworkPlotter

Interactive network plotter using Plotly.

Creates interactive visualizations of haplotype networks with hover information, zoom/pan controls, and clickable nodes.

Source code in src/pypopart/visualization/interactive_plot.py
 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
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
344
345
346
347
348
349
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
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
class InteractiveNetworkPlotter:
    """
    Interactive network plotter using Plotly.

    Creates interactive visualizations of haplotype networks with
    hover information, zoom/pan controls, and clickable nodes.
    """

    def __init__(self, network: HaplotypeNetwork):
        """
        Initialize interactive plotter with a haplotype network.

        Parameters
        ----------
        network :
            HaplotypeNetwork object to visualize.
        """
        self.network = network
        self.figure = None

    def plot(
        self,
        layout: Optional[Dict[str, Tuple[float, float]]] = None,
        layout_algorithm: str = 'spring',
        node_size_scale: float = 20.0,
        node_color_map: Optional[Dict[str, str]] = None,
        population_colors: Optional[Dict[str, str]] = None,
        edge_width_scale: float = 2.0,
        show_labels: bool = True,
        show_edge_labels: bool = True,
        median_vector_color: str = 'lightgray',
        title: Optional[str] = None,
        width: int = 1000,
        height: int = 800,
        **kwargs,
    ) -> Figure:
        """
            Create an interactive network plot.

        Parameters
        ----------
            layout :
                Pre-computed node positions {node_id: (x, y)}.
            layout_algorithm :
                NetworkX layout algorithm ('spring', 'circular', 'kamada_kawai').
            node_size_scale :
                Scaling factor for node sizes.
            node_color_map :
                Custom color mapping {node_id: color}.
            population_colors :
                Color mapping for populations {pop_name: color}.
            edge_width_scale :
                Scaling factor for edge widths.
            show_labels :
                Whether to show node labels.
            show_edge_labels :
                Whether to show edge labels with mutation counts.
            median_vector_color :
                Color for median vector nodes.
            title :
                Plot title.
            width :
                Figure width in pixels.
            height :
                Figure height in pixels.
            **kwargs :
                Additional layout arguments.

        Returns
        -------
            Plotly Figure object.
        """
        # Get graph and compute layout if not provided
        graph = self.network._graph
        if layout is None:
            layout = self._compute_layout(graph, layout_algorithm)

        # Create figure
        self.figure = go.Figure()

        # Add edges first (so they appear below nodes)
        self._add_edges(graph, layout, edge_width_scale, show_edge_labels)

        # Add nodes
        self._add_nodes(
            graph,
            layout,
            node_size_scale,
            node_color_map,
            population_colors,
            median_vector_color,
            show_labels,
        )

        # Update layout
        plot_title = title if title else self.network.name
        self.figure.update_layout(
            title={
                'text': plot_title,
                'x': 0.5,
                'xanchor': 'center',
                'font': {'size': 20},
            },
            showlegend=True,
            hovermode='closest',
            width=width,
            height=height,
            xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
            yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
            plot_bgcolor='white',
            **kwargs,
        )

        return self.figure

    def add_population_legend(self, population_colors: Dict[str, str]) -> None:
        """
        Add a legend for population colors.

        Parameters
        ----------
        population_colors :
            Color mapping for populations.
        """
        if self.figure is None:
            raise ValueError('No plot exists. Call plot() first.')

        # Add invisible traces for legend
        for pop_name, color in sorted(population_colors.items()):
            self.figure.add_trace(
                go.Scatter(
                    x=[None],
                    y=[None],
                    mode='markers',
                    marker={'size': 10, 'color': color},
                    showlegend=True,
                    name=pop_name,
                    hoverinfo='skip',
                )
            )

    def save_html(self, filename: str, auto_open: bool = False, **kwargs) -> None:
        """
        Save the interactive plot as an HTML file.

        Parameters
        ----------
        filename :
            Output filename (should end with .html).
        auto_open :
            Whether to automatically open in browser.
        **kwargs :
            Additional arguments passed to write_html().
        """
        if self.figure is None:
            raise ValueError('No plot exists. Call plot() first.')

        self.figure.write_html(filename, auto_open=auto_open, **kwargs)

    def show(self) -> None:
        """Display the interactive plot in a browser or notebook."""
        if self.figure is None:
            raise ValueError('No plot exists. Call plot() first.')

        self.figure.show()

    def _compute_layout(
        self, graph: nx.Graph, algorithm: str
    ) -> Dict[str, Tuple[float, float]]:
        """
            Compute node layout using specified algorithm.

        Parameters
        ----------
            graph :
                NetworkX graph.
            algorithm :
                Layout algorithm name.

        Returns
        -------
            Dictionary mapping node IDs to (x, y) positions.
        """
        if algorithm == 'spring':
            return nx.spring_layout(graph, k=1, iterations=50)
        elif algorithm == 'circular':
            return nx.circular_layout(graph)
        elif algorithm == 'kamada_kawai':
            return nx.kamada_kawai_layout(graph)
        elif algorithm == 'spectral':
            return nx.spectral_layout(graph)
        elif algorithm == 'shell':
            return nx.shell_layout(graph)
        else:
            raise ValueError(f'Unknown layout algorithm: {algorithm}')

    def _add_edges(
        self,
        graph: nx.Graph,
        layout: Dict[str, Tuple[float, float]],
        width_scale: float,
        show_edge_labels: bool = True,
    ) -> None:
        """
        Add edges to the plot.

        Parameters
        ----------
        graph :
            NetworkX graph.
        layout :
            Node positions.
        width_scale :
            Edge width scaling factor.
        show_edge_labels :
            Whether to show edge labels with mutation counts.
        """
        edge_traces = []
        edge_annotations = []

        for u, v in graph.edges():
            x0, y0 = layout[u]
            x1, y1 = layout[v]

            # Get edge weight
            weight = graph[u][v].get('weight', 1)

            # Calculate width (inverse of distance)
            width = width_scale * max(0.5, 3.0 / max(weight, 1))

            # Create hover text
            hover_text = f'{u} ↔ {v}<br>Distance: {weight} mutation(s)<br>'

            # Create edge trace
            edge_trace = go.Scatter(
                x=[x0, x1, None],
                y=[y0, y1, None],
                mode='lines',
                line={'width': width, 'color': 'rgba(150, 150, 150, 0.6)'},
                hoverinfo='text',
                hovertext=hover_text,
                showlegend=False,
            )

            edge_traces.append(edge_trace)

            # Add edge label annotation if requested
            if show_edge_labels and weight > 0:
                # Position label at midpoint of edge
                x_mid = (x0 + x1) / 2
                y_mid = (y0 + y1) / 2

                edge_annotations.append(
                    {
                        'x': x_mid,
                        'y': y_mid,
                        'text': str(int(weight)),
                        'showarrow': False,
                        'font': {'size': 10, 'color': 'rgba(100, 100, 100, 0.8)'},
                        'bgcolor': 'rgba(255, 255, 255, 0.7)',
                        'borderpad': 2,
                    }
                )

        # Add all edge traces
        for trace in edge_traces:
            self.figure.add_trace(trace)

        # Add edge label annotations
        if edge_annotations:
            self.figure.update_layout(annotations=edge_annotations)

    def _add_nodes(
        self,
        graph: nx.Graph,
        layout: Dict[str, Tuple[float, float]],
        size_scale: float,
        node_color_map: Optional[Dict[str, str]],
        population_colors: Optional[Dict[str, str]],
        median_vector_color: str,
        show_labels: bool,
    ) -> None:
        """
        Add nodes to the plot.

        Parameters
        ----------
        graph :
            NetworkX graph.
        layout :
            Node positions.
        size_scale :
            Node size scaling factor.
        node_color_map :
            Custom node color mapping.
        population_colors :
            Population color mapping.
        median_vector_color :
            Color for median vectors.
        show_labels :
            Whether to show node labels.
        """
        # Separate haplotypes and median vectors
        haplotype_nodes = [
            n for n in graph.nodes() if not self.network.is_median_vector(n)
        ]
        median_nodes = self.network.median_vector_ids

        # Add haplotype nodes
        if haplotype_nodes:
            self._add_node_trace(
                haplotype_nodes,
                layout,
                size_scale,
                node_color_map,
                population_colors,
                'circle',
                show_labels,
                is_median=False,
            )

        # Add median vector nodes
        if median_nodes:
            self._add_node_trace(
                median_nodes,
                layout,
                size_scale,
                dict.fromkeys(median_nodes, median_vector_color),
                None,
                'square',
                show_labels,
                is_median=True,
            )

    def _add_node_trace(
        self,
        nodes: List[str],
        layout: Dict[str, Tuple[float, float]],
        size_scale: float,
        node_color_map: Optional[Dict[str, str]],
        population_colors: Optional[Dict[str, str]],
        symbol: str,
        show_labels: bool,
        is_median: bool,
    ) -> None:
        """
        Add a trace for a group of nodes.

        Parameters
        ----------
        nodes :
            List of node IDs.
        layout :
            Node positions.
        size_scale :
            Size scaling factor.
        node_color_map :
            Custom color mapping.
        population_colors :
            Population color mapping.
        symbol :
            Marker symbol ('circle' or 'square').
        show_labels :
            Whether to show labels.
        is_median :
            Whether these are median vectors.
        """
        x_coords = []
        y_coords = []
        sizes = []
        colors = []
        texts = []
        hover_texts = []

        for node in nodes:
            # Position
            x, y = layout[node]
            x_coords.append(x)
            y_coords.append(y)

            # Get haplotype data
            hap = self.network.get_haplotype(node)

            # Size
            if is_median:
                sizes.append(size_scale * 0.8)
            elif hap:
                sizes.append(size_scale * np.sqrt(hap.frequency))
            else:
                sizes.append(size_scale * 0.5)

            # Color
            color = self._get_node_color(
                node, hap, node_color_map, population_colors, is_median
            )
            colors.append(color)

            # Label
            if show_labels:
                texts.append(node)
            else:
                texts.append('')

            # Hover text
            hover_text = self._create_hover_text(node, hap, is_median)
            hover_texts.append(hover_text)

        # Create node trace
        node_trace = go.Scatter(
            x=x_coords,
            y=y_coords,
            mode='markers+text' if show_labels else 'markers',
            marker={
                'size': sizes,
                'color': colors,
                'symbol': symbol,
                'line': {'width': 2, 'color': 'black'},
            },
            text=texts,
            textposition='top center',
            textfont={'size': 10, 'family': 'Arial Black'},
            hoverinfo='text',
            hovertext=hover_texts,
            showlegend=False,
        )

        self.figure.add_trace(node_trace)

    def _get_node_color(
        self,
        node: str,
        hap: Any,
        node_color_map: Optional[Dict[str, str]],
        population_colors: Optional[Dict[str, str]],
        is_median: bool,
    ) -> str:
        """
            Determine node color based on priority.

        Parameters
        ----------
            node :
                Node ID.
            hap :
                Haplotype object or None.
            node_color_map :
                Custom color mapping.
            population_colors :
                Population color mapping.
            is_median :
                Whether this is a median vector.

        Returns
        -------
            Color string.
        """
        if is_median:
            return 'lightgray'
        elif node_color_map and node in node_color_map:
            return node_color_map[node]
        elif population_colors and hap:
            pop_counts = hap.get_frequency_by_population()
            if pop_counts:
                # Find dominant population
                dominant_pop = max(pop_counts.items(), key=lambda x: x[1])[0]
                return population_colors.get(dominant_pop, 'lightblue')

        return 'lightblue'

    def _create_hover_text(self, node: str, hap: Any, is_median: bool) -> str:
        """
            Create hover text for a node.

        Parameters
        ----------
            node :
                Node ID.
            hap :
                Haplotype object or None.
            is_median :
                Whether this is a median vector.

        Returns
        -------
            Formatted hover text string.
        """
        lines = [f'<b>{node}</b>']

        if is_median:
            lines.append('Type: Median Vector')
        elif hap:
            lines.append(f'Frequency: {hap.frequency}')

            # Add population information
            pop_counts = hap.get_frequency_by_population()
            if pop_counts:
                lines.append('<br><b>Populations:</b>')
                for pop, count in sorted(pop_counts.items()):
                    lines.append(f'  {pop}: {count}')

            # Add sample IDs if not too many
            sample_ids = hap.sample_ids
            if len(sample_ids) <= 10:
                lines.append('<br><b>Samples:</b>')
                lines.append(', '.join(sample_ids))
            else:
                lines.append(f'<br><b>Samples:</b> {len(sample_ids)} total')

        return '<br>'.join(lines)
__init__
__init__(network: HaplotypeNetwork)

Initialize interactive plotter with a haplotype network.

Parameters:

Name Type Description Default
network HaplotypeNetwork

HaplotypeNetwork object to visualize.

required
Source code in src/pypopart/visualization/interactive_plot.py
def __init__(self, network: HaplotypeNetwork):
    """
    Initialize interactive plotter with a haplotype network.

    Parameters
    ----------
    network :
        HaplotypeNetwork object to visualize.
    """
    self.network = network
    self.figure = None
plot
plot(
    layout: Optional[Dict[str, Tuple[float, float]]] = None,
    layout_algorithm: str = "spring",
    node_size_scale: float = 20.0,
    node_color_map: Optional[Dict[str, str]] = None,
    population_colors: Optional[Dict[str, str]] = None,
    edge_width_scale: float = 2.0,
    show_labels: bool = True,
    show_edge_labels: bool = True,
    median_vector_color: str = "lightgray",
    title: Optional[str] = None,
    width: int = 1000,
    height: int = 800,
    **kwargs
) -> Figure
Create an interactive network plot.

Returns:

Type Description
Plotly Figure object.
Source code in src/pypopart/visualization/interactive_plot.py
def plot(
    self,
    layout: Optional[Dict[str, Tuple[float, float]]] = None,
    layout_algorithm: str = 'spring',
    node_size_scale: float = 20.0,
    node_color_map: Optional[Dict[str, str]] = None,
    population_colors: Optional[Dict[str, str]] = None,
    edge_width_scale: float = 2.0,
    show_labels: bool = True,
    show_edge_labels: bool = True,
    median_vector_color: str = 'lightgray',
    title: Optional[str] = None,
    width: int = 1000,
    height: int = 800,
    **kwargs,
) -> Figure:
    """
        Create an interactive network plot.

    Parameters
    ----------
        layout :
            Pre-computed node positions {node_id: (x, y)}.
        layout_algorithm :
            NetworkX layout algorithm ('spring', 'circular', 'kamada_kawai').
        node_size_scale :
            Scaling factor for node sizes.
        node_color_map :
            Custom color mapping {node_id: color}.
        population_colors :
            Color mapping for populations {pop_name: color}.
        edge_width_scale :
            Scaling factor for edge widths.
        show_labels :
            Whether to show node labels.
        show_edge_labels :
            Whether to show edge labels with mutation counts.
        median_vector_color :
            Color for median vector nodes.
        title :
            Plot title.
        width :
            Figure width in pixels.
        height :
            Figure height in pixels.
        **kwargs :
            Additional layout arguments.

    Returns
    -------
        Plotly Figure object.
    """
    # Get graph and compute layout if not provided
    graph = self.network._graph
    if layout is None:
        layout = self._compute_layout(graph, layout_algorithm)

    # Create figure
    self.figure = go.Figure()

    # Add edges first (so they appear below nodes)
    self._add_edges(graph, layout, edge_width_scale, show_edge_labels)

    # Add nodes
    self._add_nodes(
        graph,
        layout,
        node_size_scale,
        node_color_map,
        population_colors,
        median_vector_color,
        show_labels,
    )

    # Update layout
    plot_title = title if title else self.network.name
    self.figure.update_layout(
        title={
            'text': plot_title,
            'x': 0.5,
            'xanchor': 'center',
            'font': {'size': 20},
        },
        showlegend=True,
        hovermode='closest',
        width=width,
        height=height,
        xaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showticklabels': False},
        plot_bgcolor='white',
        **kwargs,
    )

    return self.figure
add_population_legend
add_population_legend(
    population_colors: Dict[str, str],
) -> None

Add a legend for population colors.

Parameters:

Name Type Description Default
population_colors Dict[str, str]

Color mapping for populations.

required
Source code in src/pypopart/visualization/interactive_plot.py
def add_population_legend(self, population_colors: Dict[str, str]) -> None:
    """
    Add a legend for population colors.

    Parameters
    ----------
    population_colors :
        Color mapping for populations.
    """
    if self.figure is None:
        raise ValueError('No plot exists. Call plot() first.')

    # Add invisible traces for legend
    for pop_name, color in sorted(population_colors.items()):
        self.figure.add_trace(
            go.Scatter(
                x=[None],
                y=[None],
                mode='markers',
                marker={'size': 10, 'color': color},
                showlegend=True,
                name=pop_name,
                hoverinfo='skip',
            )
        )
save_html
save_html(
    filename: str, auto_open: bool = False, **kwargs
) -> None

Save the interactive plot as an HTML file.

Parameters:

Name Type Description Default
filename str

Output filename (should end with .html).

required
auto_open bool

Whether to automatically open in browser.

False
**kwargs

Additional arguments passed to write_html().

{}
Source code in src/pypopart/visualization/interactive_plot.py
def save_html(self, filename: str, auto_open: bool = False, **kwargs) -> None:
    """
    Save the interactive plot as an HTML file.

    Parameters
    ----------
    filename :
        Output filename (should end with .html).
    auto_open :
        Whether to automatically open in browser.
    **kwargs :
        Additional arguments passed to write_html().
    """
    if self.figure is None:
        raise ValueError('No plot exists. Call plot() first.')

    self.figure.write_html(filename, auto_open=auto_open, **kwargs)
show
show() -> None

Display the interactive plot in a browser or notebook.

Source code in src/pypopart/visualization/interactive_plot.py
def show(self) -> None:
    """Display the interactive plot in a browser or notebook."""
    if self.figure is None:
        raise ValueError('No plot exists. Call plot() first.')

    self.figure.show()

plot_interactive_network

plot_interactive_network(
    network: HaplotypeNetwork, **kwargs
) -> Figure

Plot an interactive haplotype network.

Args: network: HaplotypeNetwork object to visualize **kwargs: Arguments passed to InteractiveNetworkPlotter.plot()

Returns:

Name Type Description
Plotly Figure object.
Example Figure

from pypopart.core.graph import HaplotypeNetwork from pypopart.visualization.interactive_plot import plot_interactive_network network = HaplotypeNetwork()

... build network ...

fig = plot_interactive_network(network, layout_algorithm='spring') fig.show()

Source code in src/pypopart/visualization/interactive_plot.py
def plot_interactive_network(network: HaplotypeNetwork, **kwargs) -> Figure:
    """
    Plot an interactive haplotype network.

    Args:
        network: HaplotypeNetwork object to visualize
        **kwargs: Arguments passed to InteractiveNetworkPlotter.plot()

    Returns
    -------
        Plotly Figure object.

    Example:
        >>> from pypopart.core.graph import HaplotypeNetwork
        >>> from pypopart.visualization.interactive_plot import plot_interactive_network
        >>> network = HaplotypeNetwork()
        >>> # ... build network ...
        >>> fig = plot_interactive_network(network, layout_algorithm='spring')
        >>> fig.show()
    """
    plotter = InteractiveNetworkPlotter(network)
    return plotter.plot(**kwargs)

create_interactive_figure

create_interactive_figure(
    network: HaplotypeNetwork,
    population_colors: Optional[Dict[str, str]] = None,
    filename: Optional[str] = None,
    auto_open: bool = False,
    **kwargs
) -> Figure

Create an interactive figure with legend.

Args: network: HaplotypeNetwork object to visualize population_colors: Color mapping for populations filename: Optional filename to save HTML file auto_open: Whether to open the file in browser **kwargs: Additional arguments passed to plot()

Returns:

Name Type Description
Plotly Figure object.
Example Figure

fig = create_interactive_figure( ... network, ... population_colors={'PopA': 'red', 'PopB': 'blue'}, ... filename='network.html' ... )

Source code in src/pypopart/visualization/interactive_plot.py
def create_interactive_figure(
    network: HaplotypeNetwork,
    population_colors: Optional[Dict[str, str]] = None,
    filename: Optional[str] = None,
    auto_open: bool = False,
    **kwargs,
) -> Figure:
    """
    Create an interactive figure with legend.

    Args:
        network: HaplotypeNetwork object to visualize
        population_colors: Color mapping for populations
        filename: Optional filename to save HTML file
        auto_open: Whether to open the file in browser
        **kwargs: Additional arguments passed to plot()

    Returns
    -------
        Plotly Figure object.

    Example:
        >>> fig = create_interactive_figure(
        ...     network,
        ...     population_colors={'PopA': 'red', 'PopB': 'blue'},
        ...     filename='network.html'
        ... )
    """
    plotter = InteractiveNetworkPlotter(network)

    # Create plot
    fig = plotter.plot(population_colors=population_colors, **kwargs)

    # Add legend if population colors provided
    if population_colors:
        plotter.add_population_legend(population_colors)

    # Save if filename provided
    if filename:
        plotter.save_html(filename, auto_open=auto_open)

    return fig