> ## Documentation Index
> Fetch the complete documentation index at: https://wiki.latch.bio/llms.txt
> Use this file to discover all available pages before exploring further.

# Viewer Widgets

> Use viewer widgets to display plots, tables, and genomic data in your notebook interface.

In Edit Mode, outputs like dataframes and figures are rendered automatically. In App Mode, no outputs are shown unless explicitly defined. Output widgets allow you to specify which elements should be visible, providing fine-grained control over the app interface.

## Supported Output Widget Types

Below is a comprehensive list of supported output widget types.

<AccordionGroup>
  <Accordion icon="chart-line" title="Plot Output">
    The Plot output widget allows you to display matplotlib Figures, SubFigures, Axes, or Plotly figures in your notebook interface.

    ```python theme={null}
    import matplotlib.pyplot as plt
    from lplots.widgets.plot import w_plot

    # Create a matplotlib figure
    fig, ax = plt.subplots()
    ax.plot([1, 2, 3], [1, 2, 3])
    ax.set_title("My Plot")

    # Display the plot in the notebook
    plot = w_plot(
        label="Example Plot", # optional label displayed above the plot
        source=fig
    )
    ```

    ### Widget Parameters

    `label`: *string* optional label displayed above the plot

    `source`: *Figure | SubFigure | Axes | BaseFigure* the plot object to display. Can be:

    * Matplotlib Figure
    * Matplotlib SubFigure
    * Matplotlib Axes
    * Plotly Figure (BaseFigure)

    `key`: *string* optional unique identifier for the widget

    ### Usage Notes

    * The plot widget automatically detects the plot title from the source object
    * The widget creates an interactive display of your plot that users can interact with
    * In the notebook outline, the plot title from the source object will be used if no label is provided

    ### Examples

    **Matplotlib Axes Example:**

    ```python theme={null}
    import matplotlib.pyplot as plt
    from lplots.widgets.plot import w_plot

    # Create plot with axes
    fig, ax = plt.subplots()
    ax.scatter([1,2,3], [1,2,3])
    ax.set_title("Scatter Plot")

    # Display just the axes
    w_plot(source=ax)
    ```

    **Plotly Figure Example:**

    ```python theme={null}
    import plotly.express as px
    from lplots.widgets.plot import w_plot

    # Create a plotly figure
    fig = px.scatter(x=[1,2,3], y=[1,2,3])
    fig.update_layout(title="Plotly Scatter")

    # Display the plotly figure
    w_plot(label="Interactive Plot", source=fig)
    ```
  </Accordion>

  <Accordion icon="table" title="Table Output">
    The Table output widget allows you to display tabular data in an interactive table format.

    ```python theme={null}
    import pandas as pd
    from lplots.widgets.table import w_table

    # Create sample dataframe
    df = pd.DataFrame({
        'A': [1, 2, 3],
        'B': ['a', 'b', 'c']
    })

    # Display the table
    table = w_table(
        label="Sample Data",
        source=df
    )
    ```

    ### Widget Parameters

    `label`: *string* optional label displayed above the table

    `source`: *DataFrame* the pandas DataFrame to display

    `key`: *string* optional unique identifier for the widget
  </Accordion>

  <Accordion icon="dna" title="IGV Viewer">
    The IGV output widget allows you to visualize and interact with your genomic data.

    ```python theme={null}
    from lplots.widgets.igv import w_igv, IGVOptions

    latch_path = f"latch://<workspace_id>.account/Covid/covid.bam"
    index_path = f"latch://<workspace_id>.account/Covid/covid.bam.bai"

    options: IGVOptions = {
      "genome": "hg38",
      "tracks": [
        {
          "name": "test",
          "type": "alignment",
          "url": latch_path,
          "indexURL": index_path,
          "minHeight": 100,
          "maxHeight": 200
        }
      ]
    }

    w_igv(options=options)
    ```

    ### Widget Parameters

    `options`: *dict* required dictionary of options for configuring the IGV browser. See [Browser Creation](https://igv.org/doc/igvjs/#Browser-Creation/#browser-configuration-options)
    for a list of available options. See [Tracks](https://igv.org/doc/igvjs/#tracks/Tracks/) for configuration options for each track.

    ### Usage Notes

    * The IGV widget accepts both Latch paths and generic URLs.
    * If a Latch path is provided without an index, the widget will automatically generate and pull an index for the file.
  </Accordion>

  <Accordion icon="cube" title="Molstar Viewer">
    The Molstar output widget allows you to visualize and interact with molecular structures using the Molstar 3D viewer. It uses [MolViewSpec (MVS)](https://molstar.org/mol-view-spec/), a toolkit for standardized description of reproducible molecular visualizations. MolViewSpec uses a tree-based approach to compose complex 3D molecular scenes from simple building blocks.

    ### Quick Start

    ```python theme={null}
    # import the Molstar widget
    from lplots.widgets.molstar import w_molstar, MolstarOptions
    # import the MolViewSpec builder
    # This is a tree-based API for defining molecular visualizations
    from molviewspec.builder import Root

    # Configure Molstar options
    options: MolstarOptions = {
        "layout": {
            "layout_shown_by_default": {
                "logs": False,
                "sequence_viewer": True,
                "right_controls": True,
                "left_controls": True
            }
        }
    }

    # Create a molstarviewspec builder and define the structure view
    builder = Root()
    # You can also use a latch:// path to load a structure from Latch Data
    builder.download(url="https://www.ebi.ac.uk/pdbe/entry-files/1cbs.bcif") \
        .parse(format="bcif") \
        .structure(type="model") \
        .component(selector="polymer") \
        .representation(type="cartoon") \
        .color(color="lightblue")

    # Display the Molstar viewer
    molstar = w_molstar(
        label="Protein Structure",
        options=options,
        molstarviewspec_builder=builder
    )
    ```

    ### Widget Parameters

    `label`: *string* optional label displayed above the viewer

    `options`: *MolstarOptions* required dictionary for configuring the Molstar viewer layout. Contains:

    * `layout`: Layout configuration options
      * `layout_shown_by_default`: Controls visibility of UI elements
        * `logs`: *bool* - Show/hide logs panel by default
        * `sequence_viewer`: *bool* - Show/hide sequence viewer by default
        * `right_controls`: *bool* - Show/hide right control panel by default
        * `left_controls`: *bool* - Show/hide left control panel by default

    `molstarviewspec_builder`: *Root | None* optional MolViewSpec builder for defining the molecular structure view

    `key`: *string* optional unique identifier for the widget

    ### Widget Value

    The Molstar widget returns selection data when users interact with the structure:

    ```python theme={null}
    # Access the current selection
    selection = molstar.value

    if selection['selection'] is not None:
        # Access selected segments
        for segment in selection['selection']['segments']:
            chain_id = segment['chain_id']
            sequence = segment['sequence']

            # Access individual residues
            for residue in segment['residues']:
                print(f"Chain: {residue['chain_id']}, "
                      f"Residue: {residue['residue_name']}, "
                      f"Number: {residue['residue_number']}")
    ```

    ### Selection Data Structure

    When users select residues in the viewer, the widget returns:

    * `selection`: *SequenceSelection | None* - Contains:
      * `segments`: List of selected sequence segments
      * `full_sequence`: Complete sequence string
      * `structure_label`: Optional label for the structure
      * Each segment contains:
        * `chain_id`: Chain identifier
        * `residues`: List of selected residues with detailed information
        * `sequence`: Sequence string for the segment
        * `start_residue` and `end_residue`: Segment boundaries

    ### MolViewSpec Builder

    The MolViewSpec builder provides a powerful tree-based API for defining molecular visualizations. The builder supports:

    * **Download & Parse**: Load structures from URLs in various formats (PDB, mmCIF, bcif)
    * **Structure**: Create structures with support for assemblies, crystal symmetry, and multi-model structures
    * **Component**: Select substructures by chain, residue range, or custom selectors
    * **Representation**: Define visualization modes (cartoon, ball-and-stick, surface, etc.)
    * **Color**: Apply custom colors and opacity to selections
    * **Label & Tooltip**: Add text labels and interactive tooltips
    * **Camera & Focus**: Control camera position and orientation
    * **Volumetric Data**: Render electron density maps
    * **Primitives**: Draw custom shapes (ellipses, boxes, arrows, meshes)
    * **Annotations**: Create data-driven components with external annotation files

    For complete documentation, see the [MolViewSpec documentation](https://molstar.org/mol-view-spec-docs/).

    ### Usage Notes

    * The Molstar widget is fully interactive, allowing users to rotate, zoom, and select parts of the structure
    * Use the `molstarviewspec_builder` parameter to programmatically define the initial view and styling
    * The `value` property provides reactive access to the current selection
    * MolViewSpec supports both remote URLs and Latch paths for loading structure files
    * The builder uses a chainable API for building complex visualizations incrementally
  </Accordion>
</AccordionGroup>

## Output Widget Reactivity

Output widgets are reactive to changes in their source data. When the source plot or data is updated, the widget display will automatically update to reflect the changes.

**Example:**

```python theme={null}
import matplotlib.pyplot as plt
from lplots.widgets.plot import w_plot

# Create initial plot
fig, ax = plt.subplots()
line, = ax.plot([1, 2, 3], [1, 2, 3])
ax.set_title("Dynamic Plot")

# Display the plot
plot = w_plot(label="Updating Plot", source=fig)

# Update the plot data
line.set_ydata([2, 1, 3])
fig.canvas.draw()  # Plot will automatically update in the widget
```
