mols2grid
mols2grid turns a DataFrame with a SMILES column into a searchable, sortable grid of 2D chemical structures, drawn by RDKit – pagination, free-text and substructure (SMARTS) search, and a checkbox selection, with no JavaScript to write. @render_mols2grid adds two accessors: .selected() for the checkbox set and .clicked() for a click on a structure’s image.

The quick start output – 257 molecules from the Delaney solubility dataset, searchable and sortable out of the box. Try the app.
Installation
pip install 'shinywidgets[mols2grid]'This installs mols2grid, rdkit (used for SDF parsing and server-side descriptors), pandas, and anywidget. Installing the extra pins a compatible mols2grid version automatically.
Quick start
Return any DataFrame with a SMILES column (the default smiles_col) and you get a full grid: pagination, sorting, and both text and substructure search, with zero other code. This example uses the solubility dataset mols2grid ships for its own examples (257 molecules from the Delaney/ESOL dataset).
from __future__ import annotations
import mols2grid
from shiny.express import ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid quickstart", fillable=True)
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
with ui.card(full_screen=True):
@render_mols2grid(subset=["ID"], tooltip=["ID", "NAME", "SOL"])
def grid():
return mols
Overview
A look at what you can build. Click any of them to open the app, with its code, in Shinylive.
A full chemical dataset explorer
Click a molecule for its descriptors
Selection drives a table, chart, and SDF download
Lasso a descriptor scatter to filter the grid
Filter the grid from Shiny sliders
See exactly what a click reports
See exactly what the checkbox selection reports
Style cells and format fields
Draw every depiction server-side
Bound the grid’s height
A minimal starting template
Grid features
Each of the following is a plain mols2grid option – nothing Shiny-specific yet.
Text and SMARTS search
Every grid gets a search box with no code: type a word and it matches against whatever’s in subset/tooltip (here, the molecule’s common name); switch to SMARTS and it matches a structural pattern, computed by RDKit in the browser, with the matched substructure highlighted in red on every result.


Styling and field formatting
subset controls which columns appear under each structure ("img" is the depiction itself, so include it explicitly once you customize subset); tooltip adds columns to the hover popover instead; sort_by picks the initial sort column; and transform reformats a field’s displayed text (not its underlying value, so sorting and selection are unaffected) – handy for adding units or rounding a float. border, gap, background_color, and hover_color restyle the cells themselves.
from __future__ import annotations
import mols2grid
from shiny.express import ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid: fields, styling, and transform", fillable=True)
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
with ui.card(full_screen=True):
@render_mols2grid(
subset=["NAME", "img", "SOL"],
tooltip=["NAME", "SOL_classification"],
sort_by="SOL",
# transform only affects display text (in subset/tooltip fields), not
# the underlying value used for sorting/selection
transform={"SOL": lambda x: f"logS {x:.1f}"},
border="2px solid #cfe2ff",
background_color="#f8fbff",
hover_color="#dbe9ff",
gap=6,
n_items_per_page=12,
)
def grid():
return mols
Server-side depictions with prerender=True
By default each structure is drawn by RDKit’s WebAssembly build running in the visitor’s browser. Passing prerender=True draws every depiction once, server-side, with the RDKit Python bindings, and embeds the images directly – useful if you’d rather spend CPU on your server than on each visitor’s browser, especially for very large grids. The grid looks identical either way; what changes is where the drawing happens, and that substructure highlighting in search results stops working, since that needs a client-side redraw. RDKit still loads client-side either way, to power the SMARTS search box itself.
from __future__ import annotations
import mols2grid
from shiny.express import ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid with prerender=True", fillable=True)
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
with ui.card(full_screen=True):
# prerender=True draws every depiction server-side with RDKit and embeds
# the images directly, so the browser never redraws them -- but the page
# still loads RDKit MinimalLib (it powers the SMARTS search box) plus
# jQuery, Bootstrap, and list.js from CDNs, so this does not make the grid
# work offline, and substructure-match highlighting is unavailable (it
# needs per-cell client-side redraws).
@render_mols2grid(subset=["ID"], tooltip=["ID", "SOL"], prerender=True)
def grid():
return mols
Reacting to interaction
Every @render_mols2grid output has two accessors: grid.selected() reports the checkbox set, and grid.clicked() reports the last structure clicked. Call either from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the user does it again.
Click for a detail card
A click is for drilling into one molecule: render a bigger RDKit depiction and a few computed descriptors next to the grid, driven entirely by grid.clicked().
from __future__ import annotations
import matplotlib.pyplot as plt
import mols2grid
from rdkit import Chem
from rdkit.Chem import Descriptors, Draw
from shiny import render, req
from shiny.express import ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid: click -> detail card", fillable=True)
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
ui.card_header("Click a molecule's image")
@render_mols2grid(clicks=True, subset=["ID"], n_items_per_page=12)
def grid():
return mols
with ui.card():
ui.card_header("Detail card")
@render.plot
def depiction():
row = grid.clicked()
req(row is not None)
mol = Chem.MolFromSmiles(row["SMILES"])
fig, ax = plt.subplots(figsize=(4, 3))
ax.imshow(Draw.MolToImage(mol, size=(400, 300)))
ax.axis("off")
return fig
@render.ui
def descriptors():
row = grid.clicked()
if row is None:
return ui.p("Click a molecule to see its descriptors.")
mol = Chem.MolFromSmiles(row["SMILES"])
rows = {
"ID": row["ID"],
"MW": f"{Descriptors.MolWt(mol):.1f}",
"LogP": f"{Descriptors.MolLogP(mol):.2f}",
"TPSA": f"{Descriptors.TPSA(mol):.1f}",
"H-bond donors": Descriptors.NumHDonors(mol),
"H-bond acceptors": Descriptors.NumHAcceptors(mol),
"Rotatable bonds": Descriptors.NumRotatableBonds(mol),
}
return ui.tags.table(
*[ui.tags.tr(ui.tags.td(k), ui.tags.td(v)) for k, v in rows.items()]
)

The detail card recomputes its descriptors with RDKit on the server, from the row’s SMILES – clicked() gives you the data to look a molecule up, not a pre-computed descriptor set.
Selection drives multiple views
grid.selected() is just row indices – look them up in your source DataFrame and feed the result to as many downstream outputs as you want: a table, a chart, a file download. All three update together, from one shared helper function.
from __future__ import annotations
import io
import mols2grid
import pandas as pd
import plotly.express as px
from rdkit import Chem
from rdkit.Chem import Descriptors
from shiny import render
from shiny.express import ui
from shinywidgets import render_mols2grid, render_plotly
def load_molecules() -> pd.DataFrame:
df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
df = df[["SMILES", "ID", "SOL"]].rename(columns={"SOL": "LogS"})
df["MW"] = [
round(Descriptors.MolWt(m), 1) if (m := Chem.MolFromSmiles(s)) else None
for s in df["SMILES"]
]
return df.dropna(subset=["MW"]).reset_index(drop=True)
MOLS = load_molecules()
ui.page_opts(title="mols2grid: selection -> table, chart, download", fillable=True)
with ui.layout_columns(col_widths=[7, 5]):
with ui.card(full_screen=True):
ui.card_header("Pick some molecules")
@render_mols2grid(subset=["ID"], tooltip=["ID", "MW", "LogS"])
def grid():
return MOLS
with ui.layout_columns(col_widths=12):
with ui.card():
ui.card_header("Selected molecules")
@render.data_frame
def table():
return render.DataGrid(selected_rows(), width="100%")
@render.download_button(
filename="selected_molecules.sdf", label="Download selection as SDF"
)
def download():
writer_out = io.StringIO()
writer = Chem.SDWriter(writer_out)
for smiles, id_ in zip(selected_rows()["SMILES"], selected_rows()["ID"]):
mol = Chem.MolFromSmiles(smiles)
if mol is not None:
mol.SetProp("_Name", str(id_))
writer.write(mol)
writer.close()
yield writer_out.getvalue()
with ui.card():
ui.card_header("Molecular weight of the selection")
@render_plotly
def hist():
return px.histogram(selected_rows(), x="MW", nbins=10)
def selected_rows() -> pd.DataFrame:
# Positional row indices from the browser, looked up directly in MOLS
# (the same frame and row order the grid was built from)
idx = [int(k) for k in (grid.selected() or {})]
return MOLS.loc[idx]

Checking cells populates the table and the histogram together; clicking “Download selection as SDF” produces a matching SD file.
Updating in place
grid.grid.filter(mask) hides non-matching rows in the grid that’s already on screen, keeping the user’s scroll position, sort, and checkbox selection. This is almost always what you want for “a Shiny input narrows the grid” – the alternative, re-running the render function with a pre-filtered DataFrame, re-sends the whole grid document on every change and drops the in-progress selection.
from __future__ import annotations
import mols2grid
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Descriptors
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid: filter from Python", fillable=True)
def load_molecules() -> pd.DataFrame:
df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
df = df[["SMILES", "ID"]].reset_index(drop=True)
mw, logp = [], []
for smiles in df["SMILES"]:
mol = Chem.MolFromSmiles(smiles)
mw.append(round(Descriptors.MolWt(mol), 1) if mol else float("nan"))
logp.append(round(Descriptors.MolLogP(mol), 2) if mol else float("nan"))
df["MW"], df["LogP"] = mw, logp
return df.dropna(subset=["MW"]).reset_index(drop=True)
MOLS = load_molecules()
mw_lo, mw_hi = float(MOLS["MW"].min()), float(MOLS["MW"].max())
logp_lo, logp_hi = float(MOLS["LogP"].min()), float(MOLS["LogP"].max())
with ui.sidebar():
ui.input_slider("mw", "Molecular weight", min=mw_lo, max=mw_hi, value=(mw_lo, mw_hi))
ui.input_slider("logp", "LogP", min=logp_lo, max=logp_hi, value=(logp_lo, logp_hi))
with ui.card(full_screen=True):
@render_mols2grid(subset=["ID"], tooltip=["ID", "MW", "LogP"])
def grid():
# Runs once: the sliders filter the already-rendered grid below
# instead of re-running this function, so the grid document (and its
# ~50 KB+ of boilerplate HTML) isn't re-sent on every drag.
return MOLS
@reactive.effect
def _filter():
# grid.grid is None until the first render; filter() updates the
# browser's list.js view in place without rebuilding the iframe, so
# pagination/sort/search state (and any selection) survives.
if grid.grid is None:
return
lo, hi = input.mw()
plo, phi = input.logp()
mask = MOLS["MW"].between(lo, hi) & MOLS["LogP"].between(plo, phi)
grid.grid.filter(mask.tolist())No reactive.isolate() is needed here, since nothing this effect reads is also something it writes.


Dragging the molecular weight slider’s upper handle down narrows the grid instantly, with pagination, sort order, and any existing selection untouched.
Linking widgets
Pair mols2grid with plotly’s own .selected_rows() accessor for a classic “chemical space” pattern: scatter two computed descriptors, lasso a region, and filter the grid to exactly those molecules.
from __future__ import annotations
import mols2grid
import pandas as pd
import plotly.express as px
from rdkit import Chem
from rdkit.Chem import Descriptors
from shiny import reactive
from shiny.express import ui
from shinywidgets import render_mols2grid, render_plotly
def load_molecules() -> pd.DataFrame:
df = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
df = df[["SMILES", "ID"]].reset_index(drop=True)
mw, logp = [], []
for smiles in df["SMILES"]:
mol = Chem.MolFromSmiles(smiles)
mw.append(round(Descriptors.MolWt(mol), 1) if mol else float("nan"))
logp.append(round(Descriptors.MolLogP(mol), 2) if mol else float("nan"))
df["MW"], df["LogP"] = mw, logp
return df.dropna(subset=["MW"]).reset_index(drop=True)
MOLS = load_molecules()
ui.page_opts(title="mols2grid + plotly: lasso to filter the grid", fillable=True)
with ui.layout_columns(col_widths=[5, 7]):
with ui.card(full_screen=True):
ui.card_header("Lasso- or box-select points")
@render_plotly(listen_to=["selected"])
def scatter():
fig = px.scatter(MOLS, x="MW", y="LogP", custom_data=[MOLS.index])
fig.update_layout(dragmode="lasso")
return fig
with ui.card(full_screen=True):
ui.card_header("Grid filtered to the selection")
@render_mols2grid(subset=["ID"], tooltip=["ID", "MW", "LogP"])
def grid():
return MOLS
@reactive.effect
def _link():
if grid.grid is None or scatter.selected() is None:
return # nothing lassoed yet: leave every molecule visible
selected = scatter.selected_rows(MOLS)
mask = MOLS.index.isin(selected.index)
grid.grid.filter(mask.tolist())

Lassoing a cluster narrows the grid to just those molecules. The scatter.selected() is None check matters: selected_rows() alone returns an empty frame both before any lasso and after one that catches nothing, so without it the grid would start out filtered to zero molecules.
Accessor reference
| Accessor | Returns | Before any interaction | Across a re-render | Default rate policy |
|---|---|---|---|---|
selected() |
dict[int, str] ({row_index: SMILES}) |
seeded {} as soon as the grid renders |
re-seeded from the new grid – in practice usually unchanged, since mols2grid’s own cache_selection=True default restores the prior selection into it |
none |
clicked() |
dict[str, Any] (the clicked row’s data) or raises |
None until the first click (only exists with clicks=True or a callback) |
kept until the user clicks the new grid (the row data may then describe the previous render’s grid) | none |
Both read naturally in a @render.* function, a @reactive.calc, or a @reactive.effect; outside a reactive context (e.g. in a button handler) they return the current value without creating a dependency. Row indices and the mols2grid-id field are positional, against the rows as rendered – if the underlying data changes, the same index can refer to a different molecule.
Unlike every other accessor in this roster, clicked() isn’t available unless you ask for it: without clicks=True or a Python callback=, it raises RuntimeError naming the fix, rather than silently returning None:
clicked() needs the grid's click channel, which the document only renders when asked: add
clicks=True (or a Python callback=) to the @render_mols2grid decorator.
selected()
from __future__ import annotations
import mols2grid
from shiny.express import render, ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid selected() accessor", fillable=True)
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_mols2grid(subset=["ID"], tooltip=["ID", "SOL"], n_items_per_page=12)
def grid():
return mols
with ui.card():
ui.card_header("grid.selected()")
@render.code
def selected():
# {} once the grid has rendered and nothing is checked yet; each
# checkbox toggle re-runs this (positional row index -> SMILES)
return str(grid.selected())selected() is seeded with the empty dict, not None, as soon as the grid renders; checking a cell (click the cell, not just the tiny checkbox – the whole cell is the click target) publishes it, keyed by its position:


For the selected rows as a DataFrame instead of this dict, use grid.grid.get_selection().
clicked()
Clicking a molecule’s image is a distinct gesture from the selection checkbox: it’s a one-off user action, so clicked() keeps its last value across re-renders until the user clicks the new grid. It requires clicks=True (or an explicit callback=, which mols2grid uses for the same click target).
from __future__ import annotations
import mols2grid
from shiny.express import render, ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid clicked() accessor", fillable=True)
ui.tags.style("pre { white-space: pre-wrap; overflow-wrap: anywhere; }")
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
with ui.layout_columns(col_widths=[8, 4]):
with ui.card(full_screen=True):
@render_mols2grid(
clicks=True, subset=["ID"], tooltip=["ID", "SOL"], n_items_per_page=12
)
def grid():
return mols
with ui.card():
ui.card_header("grid.clicked()")
@render.code
def clicked():
# None until a molecule's image is clicked (a distinct gesture
# from the selection checkbox); keeps its value across re-renders
# until the user clicks the new grid. The row also carries an
# "img" key (the cell's raw SVG) -- drop it unless you actually
# want the markup.
row = grid.clicked()
if row is None:
return "No click yet"
return str({k: v for k, v in row.items() if k != "img"})clicks=True adds a small play-button overlay to every cell – that’s the click target, distinct from the checkbox. Clicking it publishes the row’s full data: every displayed column plus mols2grid-id, SMILES, and the raw img SVG, regardless of what you passed to subset or tooltip.


Tuning accessors
Rate limiting
rate_policy/rate_delay on render_mols2grid() are accepted for consistency with every other @render_*, but have no observable effect: neither accessor fires more than once per discrete user gesture (a checkbox toggle or a click), so there’s nothing to smooth.
.read()
There isn’t a third trait worth reading on the rendered widget: selected() and clicked() already cover its entire browser-to-Python surface.
Large data
mols2grid doesn’t fit any of the three approaches in Large data & performance cleanly: every molecule’s data is inlined into the grid’s iframe up front, regardless of pagination – the page UI only hides rows client-side, it doesn’t limit what’s sent. A large dataset becomes a large payload, sent in one widget-state message. shiny run --ws-max-size does not help here: it raises the limit on messages the server receives from the browser – it has no effect on how much the server can send. prerender=True moves drawing cost to the server; it doesn’t reduce bytes sent either. For grids beyond a few thousand rows, filter server-side in Python before constructing the grid rather than relying on the client to page through everything – that’s the only real lever.
Layout and sizing
mols2grid measures its own content and sizes the iframe to fit, so by default a grid is a content-sized block that the page scrolls past, not a canvas that stretches to fill a container. To cap the grid’s own height (independent of its container), pass iframe_height (also iframe_width, iframe_allow, iframe_sandbox): this disables mols2grid’s auto-fit, so the grid scrolls inside that fixed box instead.
from __future__ import annotations
import mols2grid
from shiny.express import ui
from shinywidgets import render_mols2grid
ui.page_opts(title="mols2grid: layout and sizing", fillable=True)
mols = mols2grid.sdf_to_dataframe(mols2grid.datafiles.SOLUBILITY_SDF)
ui.card_header("Default: the grid sizes itself to its content; the page scrolls")
with ui.card():
@render_mols2grid(subset=["ID"], n_items_per_page=12)
def fills():
return mols
ui.card_header(
'iframe_height="150px" alone: the iframe is bounded, but the filling '
"output container still stretches to the card -- empty space below"
)
with ui.card():
@render_mols2grid(subset=["ID"], n_items_per_page=24, iframe_height="150px")
def bounded():
return mols
ui.card_header('iframe_height="150px" + fill=False: the output hugs its content too')
with ui.card():
@render_mols2grid(
subset=["ID"], n_items_per_page=24, iframe_height="150px", fill=False
)
def bounded_no_fill():
return mols
The middle card is a good demonstration of a real sizing gotcha: render_mols2grid defaults fill=True, so even once iframe_height bounds the iframe to 150px, the surrounding output <div> is still a filling flex item and stretches to match its card, leaving dead space below the grid. Adding fill=False (third card) makes the output div hug its content too.
Gotchas
- The grid needs an internet connection: every grid document loads list.js, jQuery, RDKit’s WebAssembly build, and Bootstrap from CDNs. Without one, the grid renders an empty toolbar with no error.
- A
MolGridyou construct yourself needs a uniquename; the default collides across sessions and multiple grids on one page, raisingValueError. Return a plain DataFrame instead (the renderer generates a name for you) unless you need to share oneMolGridacross outputs. filter()lines a mask up against rows in the DataFrame’s order, not a row identity, and it has no effect before the grid’s first paint. There’s no way to make a grid start out already filtered other than filtering the DataFrame itself before you return it.
In the gallery
Complete apps in the gallery that use mols2grid:
Learn more
- mols2grid documentation and its GitHub repository
- RDKit – draws every structure and computes descriptors in the examples above
- plotly – descriptor scatter pairing
- itables, reactable – general-purpose tables without structure depictions