Written and maintained by CASRAI Editorial Board
Published
On this page
py3Dmol is an open-source Python library and IPython widget that provides hardware-accelerated 3D molecular visualization directly inside Jupyter notebooks, JupyterLab, and web-based computational environments. Developed by Nicholas Rego and David Koes at the University of Pittsburgh’s Department of Computational and Systems Biology, py3Dmol serves as an object-oriented Python wrapper around the WebGL-powered 3Dmol.js JavaScript library. In computational structural biology and cheminformatics workflows, researchers utilize py3Dmol to inspect macromolecular coordinates, examine protein-ligand binding pockets, visualize molecular dynamics trajectories, evaluate docking conformations, and generate interactive structural figures without relying on external desktop graphics software or legacy Java applets.
What it is used for in research
Modern structural biology and drug discovery research generate massive volumes of atomic coordinate data from X-ray crystallography, cryo-electron microscopy (cryo-EM), nuclear magnetic resonance (NMR) spectroscopy, and deep-learning predictive models such as AlphaFold and ESMFold. Traditionally, inspecting these three-dimensional conformations required exporting files to standalone desktop applications like PyMOL or UCSF Chimera, disrupting computational notebooks and breaking reproducible exploratory data analysis. The py3Dmol library solves this interface gap by embedding interactive, hardware-accelerated WebGL molecular graphics directly into the computational notebook execution flow.
A distinctive architectural advantage of py3Dmol in academic research is its two-tier execution and kernel-free persistence model. When a researcher executes a visualization command, the Python py3Dmol.view class serializes the molecular coordinates, selection criteria, styling rules, and camera orientations into declarative JavaScript statements. These statements are bundled into a self-contained HTML/JavaScript block and delivered to the browser through the IPython interactive computing kernel display protocol (using both application/3dmoljs_load.v0 and text/html MIME types). Because all rendering logic, mouse event listeners, ray-casting selections, and WebGL shader programs execute purely client-side inside the user’s web browser, the rendered view retains full 3D interactivity (orbit, pan, zoom, surface clipping) even after the active Python kernel is halted or disconnected. When researchers share static notebook exports via GitHub, NBViewer, or institutional repositories, colleagues can manipulate 3D structures without executing code or maintaining local Python environments.
In structural bioinformatics and computational chemistry labs, py3Dmol supports several primary research workflows:
- Macromolecular Structure Validation: Rapid assessment of experimental electron density fit, Ramachandran outliers, stereochemical anomalies, and steric clashes in freshly solved crystallographic or cryo-EM models deposited in the Protein Data Bank (PDB).
- Virtual Screening and Molecular Docking Analysis: In-line inspection of top-ranked ligand poses generated by docking engines (such as AutoDock Vina, smina, or Glide). Researchers visualize hydrogen bonds, salt bridges, hydrophobic contacts, and π-stacking interactions within binding pockets.
- Cheminformatics and Conformer Exploration: Seamless integration with RDKit to convert 2D SMILES strings into energy-minimized 3D conformers, enabling instant structural verification of synthetic chemical libraries, lead-like candidates, and molecular properties alongside traditional 3D plots in Python.
- Molecular Dynamics Trajectory Inspection: Loading multi-frame coordinate files from molecular dynamics simulation packages alongside analysis toolkits like MDTraj to animate conformational transitions, domain hinge motions, and ligand dissociation pathways.
- Volumetric Isosurface Visualization: Rendering electrostatic potential maps, cryo-EM density volumes, and quantum mechanical electron density contours stored in Gaussian CUBE or OpenDX formats.
py3Dmol natively supports standard structural biology file formats, including PDB (.pdb), macromolecular Crystallographic Information Framework (.cif / .mmcif), Tripos MOL2 (.mol2), MDL Structure-Data File (.sdf / .mol), Cartesian coordinate files (.xyz), Poisson-Boltzmann charge grids (.pqr), and Gaussian volumetric grids (.cube). This format versatility allows seamless integration into diverse computational pipelines across methods in molecular biology.
Install or access (official source only)
The py3Dmol package is maintained under the permissive MIT License (with the underlying 3Dmol.js library released under the BSD 3-Clause License). Researchers can install official, verified releases through standard Python package repositories across Linux, macOS, and Windows operating systems.
Installing via pip (Python Package Index)
The canonical release of py3Dmol is distributed on the Python Package Index (PyPI) under the package name py3Dmol. To install the latest stable version (version 2.5.5) inside an active virtual environment:
# Standard installation via pip
pip install py3Dmol
# Recommended environment setup with JupyterLab and scientific libraries
pip install py3Dmol jupyterlab numpy scipy biopython
Installing via Conda / Mamba (Conda-Forge)
For scientific computing clusters and bioinformatics workflows managed by Anaconda or Conda, py3Dmol is packaged within the community-maintained conda-forge channel under the lowercase package identifier py3dmol:
# Install using Conda from conda-forge
conda install -c conda-forge py3dmol
# Or using high-speed Mamba package manager
mamba install -c conda-forge py3dmol
System and Browser Prerequisites
To run py3Dmol effectively, computational biology environments must satisfy the following technical prerequisites:
- Python Runtime: Python 3.8 or newer (tested across Python 3.8 through 3.12).
- Notebook Server: Classic Jupyter Notebook (
notebook ≥ 5.0), JupyterLab (jupyterlab ≥ 3.0), Google Colaboratory, Kaggle Notebooks, or Visual Studio Code with the Jupyter extension. Unlike legacy widget packages, py3Dmol does not require custom nodejs widget build steps or separate JupyterLab frontend extension compilations because it emits self-bootstrapping HTML. - Client Browser Requirements: A modern web browser supporting HTML5 Canvas and WebGL 1.0/2.0 (Google Chrome 80+, Mozilla Firefox 75+, Apple Safari 14+, or Microsoft Edge). Hardware graphics acceleration must be enabled in browser settings to allow GPU access.
- Network Connectivity: By default, py3Dmol loads minified 3Dmol.js runtime assets dynamically from an external Content Delivery Network (CDN) at
https://cdn.jsdelivr.net/npm/[email protected]/build/3Dmol-min.js. In air-gapped laboratory workstations or secure high-performance computing clusters lacking outbound internet access, researchers must configure a local copy of3Dmol-min.jsvia thejsparameter.
Verifying Installation Integrity
To verify that py3Dmol and its rendering dependencies are correctly configured within your Python environment, execute the following diagnostic check:
import py3Dmol
import sys
print(f"Python interpreter: {sys.version.split()[0]}")
print(f"py3Dmol version: {py3Dmol.__version__}")
# Instantiate an empty test viewer canvas
test_view = py3Dmol.view(width=200, height=200)
print("py3Dmol view class successfully initialized.")
Step-by-step task (numbered, with menu names or commands exactly as in the current docs)
This protocol provides an end-to-end, reproducible research workflow for structural biology. In this protocol, we will programmatically fetch an experimental protein-ligand crystal structure (the SARS-CoV-2 main protease Mpro complexed with an inhibitor, PDB ID 6LU7), isolate catalytic residues, apply specialized representations, generate a solvent-excluded molecular surface, construct a synchronized multi-viewer grid, and export the molecular scene for publication.
Step 1: Initialize the Interactive Canvas and Fetch Experimental Coordinates
py3Dmol provides a direct programmatic query interface to retrieve atomic coordinates from the RCSB Protein Data Bank without manual browser downloads. Create a Jupyter notebook cell and initialize the viewer using the py3Dmol.view constructor:
import py3Dmol
# Step 1: Initialize canvas and query the RCSB PDB for structure 6LU7
# Canvas dimensions are set in pixels; query fetches coordinate stream
viewer = py3Dmol.view(query='pdb:6LU7', width=700, height=500)
# Set neutral laboratory background color (white or black)
viewer.setBackgroundColor('white')
Step 2: Apply Global Secondary Structure Ribbon Representation
Configure the macromolecular backbone styling. In structural biology publications, secondary structure elements (α-helices and β-sheets) are standardly rendered in cartoon ribbon format. We use setStyle() with an empty selection dictionary {} to apply styles globally:
# Step 2: Render protein chains in cartoon representation
# 'spectrum' maps a rainbow gradient from N-terminus (blue) to C-terminus (red)
viewer.setStyle({}, {'cartoon': {'color': 'spectrum', 'opacity': 0.85}})
Step 3: Isolate and Highlight the Co-Crystallized Small-Molecule Inhibitor
Target the co-crystallized peptidomimetic inhibitor (ligand residue name N3 in structure 6LU7). We apply atom selection dictionaries to specify residue names (resn) and render the inhibitor as high-contrast ball-and-stick representations using addStyle():
# Step 3: Target the ligand (resn 'N3') using atom selection grammar
# Render ligand atoms with sticks and element-based coloring
viewer.addStyle(
{'resn': 'N3'},
{
'stick': {'colorscheme': 'greenCarbon', 'radius': 0.25},
'sphere': {'scale': 0.3, 'colorscheme': 'greenCarbon'}
}
)
Step 4: Target Active Site Binding Pocket Residues Using Proximity Queries
To inspect non-covalent interactions within the binding cavity, identify all receptor amino acids located within 5.0 Ångströms of the ligand. py3Dmol supports spatial queries via the within parameter:
# Step 4: Spatial proximity selection for catalytic dyad and pocket residues
# Selects all atoms within 5.0 Å of any atom in residue N3
pocket_selection = {'within': {'distance': 5.0, 'sel': {'resn': 'N3'}}}
# Highlight pocket sidechains as distinct sticks
viewer.addStyle(
pocket_selection,
{'stick': {'colorscheme': 'cyanCarbon', 'radius': 0.15}}
)
# Specifically label the catalytic dyad: Cys145 and His41
viewer.addResLabels(
{'resi': [41, 145]},
{
'fontSize': 12,
'fontColor': 'black',
'backgroundColor': 'rgba(255, 255, 255, 0.8)',
'backgroundOpacity': 0.8,
'showBackground': True
}
)
Step 5: Generate a Solvent-Excluded Molecular Surface for Pocket Cavity Analysis
Compute and overlay a client-side molecular surface to visualize pocket volume and steric complementarity. py3Dmol defines four distinct surface calculation algorithms via numeric constants: py3Dmol.VDW = 1 (van der Waals), py3Dmol.MS = 2 (molecular surface), py3Dmol.SAS = 3 (solvent-accessible surface), and py3Dmol.SES = 4 (solvent-excluded surface). We compute an SES restricted to the active site:
# Step 5: Compute solvent-excluded surface (SES) over the binding region
viewer.addSurface(
py3Dmol.SES,
{
'opacity': 0.55,
'color': 'white',
'wireframe': False
},
{'within': {'distance': 6.0, 'sel': {'resn': 'N3'}}}
)
Step 6: Center Viewport, Adjust Clipping Planes, and Render View
Calibrate the virtual camera by zooming into the binding site and triggering the final WebGL render pipeline:
# Step 6: Center and orient camera on the ligand binding complex
viewer.zoomTo({'resn': 'N3'})
# Render the interactive canvas into the notebook output cell
viewer.show()
Step 7: Build Synchronized Multi-Panel Comparison Grids (Viewer Grids)
In comparative structural analyses (such as evaluating wild-type vs. mutant enzymes, or apo vs. holo states), researchers require synchronized multi-canvas views. py3Dmol provides the viewergrid parameter to generate multi-panel layouts with coupled rotation and zoom controls:
# Step 7: Construct a 1x2 linked comparison grid
# viewergrid accepts a tuple of (rows, columns); linked=True synchronizes camera rotation
grid_view = py3Dmol.view(
viewergrid=(1, 2),
width=800,
height=400,
linked=True
)
# Fetch coordinate structures into individual grid cells (row, column)
# Panel (0, 0): Apo main protease (PDB: 7BQY)
grid_view.addModel(open("7BQY.pdb", "r").read(), "pdb", viewer=(0, 0))
grid_view.setStyle({'cartoon': {'color': 'lightblue'}}, viewer=(0, 0))
grid_view.addLabel("Apo Form (7BQY)", {'position': {'x': 0, 'y': 0, 'z': 0}}, viewer=(0, 0))
grid_view.zoomTo(viewer=(0, 0))
# Panel (0, 1): Holo inhibitor-bound main protease (PDB: 6LU7)
grid_view.addModel(open("6LU7.pdb", "r").read(), "pdb", viewer=(0, 1))
grid_view.setStyle({'cartoon': {'color': 'lightgreen'}}, viewer=(0, 1))
grid_view.addStyle({'resn': 'N3'}, {'stick': {'colorscheme': 'redCarbon'}}, viewer=(0, 1))
grid_view.addLabel("Holo Complex (6LU7)", {'position': {'x': 0, 'y': 0, 'z': 0}}, viewer=(0, 1))
grid_view.zoomTo(viewer=(0, 1))
# Render synchronized comparison grid
grid_view.show()
Step 8: Export Interactive Molecular Scenes to Standalone HTML
To archive interactive 3D visualizations for peer-reviewed journal supplementary information or laboratory dashboards, export the complete scene to an autonomous HTML document via write_html():
# Step 8: Export the active viewer to a self-contained HTML file
# Setting fullpage=True stretches the WebGL canvas to fill 100% viewport width and height
viewer.write_html("sars_cov2_mpro_binding_pocket.html", fullpage=True)
print("Interactive HTML export complete. File can be viewed in any web browser without Python.")
Output and how to read it
Interpreting the rendered output of py3Dmol requires understanding structural representations, element color standards, and spatial interaction cues displayed within the WebGL canvas.
Macromolecular Topology and Secondary Structure
When rendered using the cartoon representation, the protein backbone trajectory conveys structural fold and secondary structure geometry:
- α-Helices: Rendered as smooth spiral ribbons or solid coiled cylinders, illustrating tightly coiled polypeptide regions stabilized by regular (i → i+4) hydrogen bonds.
- β-Sheets: Rendered as flat directional arrows (ribbon arrows pointing from the N-terminus toward the C-terminus), revealing extended polypeptide chains forming parallel or anti-parallel pleated sheets.
- Loops and Disordered Coils: Rendered as thin cylindrical tubes connecting regular secondary structure elements. Wide loops typically indicate higher structural flexibility, often corresponding to elevated crystallographic B-factors.
Atom and Element Color Coding Standards
In stick, sphere, and line representations, py3Dmol adheres to universal Corey-Pauling-Koltun (CPK) chemical element color standards, enabling rapid identification of chemical moieties:
| Element | Symbol | Standard CPK Color | Structural Function in Macromolecules |
|---|---|---|---|
| Carbon | C | Gray / Green / Cyan (User Configurable) | Backbone and sidechain hydrophobic core scaffolds. |
| Oxygen | O | Red | Carbonyl groups, carboxylates, hydroxyls, water molecules. |
| Nitrogen | N | Blue | Amide backbone, basic amino acid sidechains (Lys, Arg, His). |
| Sulfur | S | Yellow | Cysteine thiol groups, disulfide bridges, methionine thioethers. |
| Phosphorus | P | Orange | Nucleic acid phosphodiester backbones, phosphorylated residues. |
| Hydrogen | H | White | Protons involved in hydrogen bonding networks. |
Evaluating Molecular Surfaces and Binding Cavities
The solvent-excluded surface (SES) calculated in Step 5 simulates rolling a spherical probe of radius 1.4 Å (approximating a water molecule) over the atomic van der Waals spheres. When reading the resulting surface:
- Concave Crevices: Represent hydrophobic pockets and active site clefts capable of sheltering small-molecule drugs from bulk solvent.
- Convex Ridges: Indicate solvent-exposed peptide turns and loop regions available for macromolecular partner recognition.
- Steric Clashes: Interpenetration between ligand atomic spheres and the receptor molecular surface denotes geometric strain or improper docking coordinates requiring force-field relaxation.
Programmatic Image Capture for Research Publications
To produce static raster figures for manuscripts or slide presentations, py3Dmol exposes the png() method. When called in a notebook cell following viewer initialization, it extracts a base64-encoded PNG image data URI directly from the active WebGL rendering buffer:
# Extract rendered canvas as static PNG image inside Jupyter
viewer.png()
For high-resolution print figures (300+ DPI), researchers should configure large initial canvas pixel dimensions (e.g., width=2400, height=1800) prior to rendering, capture the resulting canvas via view.png(), or export to HTML via write_html() and capture vector-quality or high-DPI screenshots via headless Chromium browsers.
Troubleshooting
When running py3Dmol across heterogeneous laboratory computing setups, researchers may encounter common technical issues. Below are verified failure modes and their exact operational remedies.
1. Canvas Displays Blank Area or “3Dmol.js failed to load” Warning
Cause: By default, py3Dmol fetches the minified JavaScript runtime from an external CDN (https://cdn.jsdelivr.net/npm/3dmol@...). If the host workstation is offline, behind an institutional firewall that restricts raw CDN scripts, or subject to strict Content Security Policies (CSP), the script download fails.
Remedy: Provide a local or internally hosted path to 3Dmol-min.js when instantiating the viewer using the js parameter:
# Use a locally cached or internal mirror script path
viewer = py3Dmol.view(
query='pdb:1ubq',
js='http://localhost:8888/static/3Dmol-min.js'
)
2. WebGL Context Loss or Black Canvas in Virtualized Environments
Cause: Running Jupyter instances inside Docker containers, headless remote SSH sessions with X11 forwarding, or cloud virtual machines lacking hardware GPU acceleration can trigger WebGL context initialization failures. Browsers restrict the maximum number of concurrent WebGL contexts (typically 8 to 16 active contexts per browser tab).
Remedy: In Google Chrome, navigate to chrome://settings/system and ensure “Use graphics acceleration when available” is enabled. If many viewer cells have executed in a single notebook, purge older contexts by clearing the notebook output cells (Kernel -> Restart & Clear Output) or by calling viewer.clear() before instantiating new models.
3. Flat 2D Molecules When Integrating with RDKit
Cause: When generating molecular structures from SMILES strings with RDKit, molecules are instantiated without 3D atomic coordinates. If a 2D mol block is passed directly to viewer.addModel(mol_data, 'mol'), the molecule appears completely flat or collapses along the Z-axis.
Remedy: Always compute 3D conformer coordinates using RDKit’s Distance Geometry algorithm (AllChem.EmbedMolecule) and minimize geometry with Merck Molecular Force Field (MMFF94) prior to visualization:
from rdkit import Chem
from rdkit.Chem import AllChem
import py3Dmol
# Generate 3D conformer coordinates in RDKit
mol = Chem.MolFromSmiles("CC(=O)Oc1ccccc1C(=O)O") # Aspirin
mol = Chem.AddHs(mol)
AllChem.EmbedMolecule(mol, randomSeed=42)
AllChem.MMFFOptimizeMolecule(mol)
# Pass valid 3D MolBlock to py3Dmol
mol_block = Chem.MolToMolBlock(mol)
view = py3Dmol.view(width=400, height=300)
view.addModel(mol_block, 'mol')
view.setStyle({'stick': {}})
view.zoomTo()
view.show()
4. Browser Freezing on Large Structures or Multi-Frame Trajectories
Cause: Loading massive multi-million atom systems (such as complete viral capsids or unstripped all-atom molecular dynamics trajectories) exhausts browser memory and saturates WebGL vertex buffer allocations, freezing the browser UI thread.
Remedy: Strip solvent water molecules (HOH) and counterions (NA, CL) before passing coordinate strings to py3Dmol. For trajectory animations, downsample the frame rate using trajectory slicing (e.g. loading every 10th or 50th frame via MDTraj) and avoid applying continuous molecular surfaces across multi-frame animation series.
5. View Centering Off-Screen or Clipped by Near/Far Planes
Cause: Setting complex styling rules or adding custom surfaces without resetting the virtual camera target causes the scene bounding sphere to exceed the WebGL clipping frustum.
Remedy: Explicitly invoke viewer.zoomTo() as the final configuration step immediately prior to viewer.show(). Pass an explicit selection dictionary (e.g. viewer.zoomTo({'chain': 'A'})) to focus camera optics strictly on the region of interest.
Free alternatives (table)
Computational biology researchers choose among several open-source and free molecular graphics software packages depending on their requirements for notebook integration, publication ray-tracing, trajectory frame rate, and web deployment. The table below details free, open-source, and academic alternatives to py3Dmol.
| Tool Name | Primary Developer / Operator | Rendering Engine & Architecture | Jupyter Notebook Integration | Headless & Export Formats | Software License | Best Research Use Case |
|---|---|---|---|---|---|---|
| py3Dmol | University of Pittsburgh (Koes Lab) | WebGL 1.0/2.0 via 3Dmol.js; client-side browser execution. | Native static HTML/JS display; kernel-free persistent sharing. | Standalone HTML (write_html), base64 PNG (png()). |
MIT / BSD 3-Clause | Lightweight, zero-dependency 3D visualization in Jupyter notebooks and shareable reports. |
| NGLView | ASBMB / NGL Development Team | WebGL via NGL.js; bidirectional ipywidgets communication. | Bidirectional widget; requires active Python kernel. | Static PNG, animated GIF, movie trajectory export. | MIT License | Interactive molecular dynamics trajectory playback and real-time Python state synchronization. |
| Mol* (Molstar) | RCSB PDB, PDBe, CEITEC | WebGL2 / WebGPU; TypeScript framework with streaming binary CIF. | Via third-party wrappers (molstar-python, ipymolstar). | PNG, MP4, State JSON, glTF 3D mesh files. | MIT License | Web portal embedding, ultra-large macromolecular assemblies, and cryo-EM map visualization. |
| PyMOL Open-Source | Schrödinger, Inc. / Community | Desktop OpenGL; native C/C++ graphics engine with Python API. | Indirect (spawns separate window or IPyMOL static image renders). | Ray-traced PNG, VRML, POV-Ray, OBJ, PSE session files. | Open-Source (Python-like / BSD-style) | High-resolution publication figures with built-in ray-tracing and complex structural editing. |
| UCSF ChimeraX | Resource for Biocomputing, Visualization, and Informatics (UCSF) | Desktop OpenGL 3.3+ via Qt GUI; Python 3 engine. | External GUI or remote server REST protocol (chimerax-web). | High-res PNG, TIFF, MP4 movie, VRML, GLTF, STL 3D printing. | Free for Academic / Non-Commercial Use | Cryo-EM density segmentation, map-fitting, integrative structural models, and VR exploration. |
| JSmol / Jmol | Jmol Development Team | HTML5 2D Canvas or WebGL via Java-to-JavaScript compilation. | Via jupyter-jmol extension (limited maintenance). | PNG, JPG, Jmol script (.spt), Web page export. | GNU LGPL v2.1 | Chemical education, browser-based crystallographic symmetry exploration, and legacy web pages. |
For research data sharing and automated notebook reports, the structured data table below compares the complete architectural attributes, rendering limits, and deployment specifications across these computational tools.
FAQ
What is the difference between 3Dmol.js and py3Dmol?
3Dmol.js is the core JavaScript library that directly handles WebGL rendering, atom coordinates, surface calculations, and mouse events in modern web browsers. py3Dmol is the official Python wrapper package designed specifically for IPython and Jupyter notebook environments. py3Dmol provides a Pythonic API that translates method calls into JavaScript strings and injects them into notebook display cells, allowing Python programmers to utilize 3Dmol.js without writing raw JavaScript.
Does py3Dmol require an active Python kernel to display molecular structures?
No. One of py3Dmol’s primary architectural strengths is kernel-free persistence. When a notebook cell executes, py3Dmol generates static HTML and JavaScript containing the coordinate data and rendering instructions. All subsequent rendering, rotation, zooming, and surface interactions execute purely inside the client web browser’s WebGL engine. When notebooks are saved and exported as static HTML or viewed on GitHub / NBViewer, the 3D molecular models remain fully interactive without requiring a running Python kernel.
How do you visualize small molecules from RDKit in py3Dmol?
To visualize small molecules generated or processed in RDKit, first generate three-dimensional coordinates using RDKit’s conformer embedding (AllChem.EmbedMolecule(mol)) and optimize geometry using a force field (AllChem.MMFFOptimizeMolecule(mol)). Convert the molecule object into a standard MolBlock string using Chem.MolToMolBlock(mol), then pass this string to py3Dmol using viewer.addModel(mol_block, 'mol'). Apply stick or sphere styling and call viewer.zoomTo() before viewer.show().
Can py3Dmol animate molecular dynamics trajectories?
Yes. py3Dmol supports multi-frame coordinate files and trajectory animations. You can load multi-model PDB files or trajectory frames using viewer.addModelsAsFrames(data, 'pdb'). To animate conformational fluctuations, invoke viewer.animate({'loop': 'forward', 'step': 1}). For large MD trajectories generated by packages such as GROMACS, AMBER, or NAMD, it is recommended to process and downsample frames using MDTraj or ProDy (often saved in HDF5 structures via h5py) prior to loading coordinates into py3Dmol.
What atom selection criteria are supported in py3Dmol?
py3Dmol provides a rich selection grammar passed as Python dictionaries to styling and manipulation methods. Key selection parameters include resi (residue sequence number or list of numbers, e.g. [41, 145]), chain (polypeptide chain ID, e.g. 'A'), resn (three-letter residue or ligand name, e.g. 'LIG'), atom (specific atom name, e.g. 'CA'), elem (chemical element symbol, e.g. 'C', 'N'), within (spatial distance queries relative to another selection), and invert (boolean flag to select the inverse subset).
How do you export high-resolution figures from py3Dmol for journal manuscripts?
You can export figures directly inside Jupyter by calling viewer.png(), which returns a base64-encoded PNG image rendered from the current WebGL canvas buffer. For publication-quality 300 DPI figures, instantiate the viewer with larger canvas dimensions (such as width=2400, height=1800) prior to calling png(), or export the interactive scene to a standalone HTML file using viewer.write_html('figure.html', fullpage=True) and capture high-resolution screenshots using a browser rendering tool.
How does py3Dmol compare to NGLView for Jupyter notebooks?
py3Dmol and NGLView serve complementary roles in computational structural biology. py3Dmol uses a static HTML/JavaScript architecture that does not require an active Python kernel after rendering, making it ideal for sharing reproducible notebooks on GitHub, exporting standalone HTML reports, and rapid data exploration. NGLView is built as a bidirectional ipywidget, which maintains active two-way communication between Python and JavaScript. This enables NGLView to stream large molecular dynamics trajectories frame-by-frame and synchronize user mouse selections back into Python variables, but requires an active kernel to function.
How do you calculate and display molecular surfaces in py3Dmol?
Molecular surfaces are generated using the viewer.addSurface() method. py3Dmol provides four distinct surface algorithms via numeric constants: py3Dmol.VDW (van der Waals surface), py3Dmol.MS (molecular surface), py3Dmol.SAS (solvent-accessible surface), and py3Dmol.SES (solvent-excluded surface). The method accepts parameters controlling surface opacity, color schemes, wireframe rendering, and spatial selections to restrict calculation to specific binding pockets.
Sources (official docs)
- Rego, N., & Koes, D. (2015). 3Dmol.js: molecular visualization with WebGL. Bioinformatics, 31(8), 1322–1324. https://doi.org/10.1093/bioinformatics/btu829. Retrieved November 13, 2026.
- University of Pittsburgh, Department of Computational & Systems Biology. (2026). 3Dmol.js GLViewer API Reference and Documentation. 3Dmol.js Project. Retrieved November 13, 2026, from https://3dmol.org/doc/GLViewer.html
- Python Package Index. (2026). py3Dmol: An IPython interface for embedding 3Dmol.js views in Jupyter notebooks (Release 2.5.5). Python Software Foundation. Retrieved November 13, 2026, from https://pypi.org/project/py3Dmol/
- 3Dmol.js Development Team. (2026). 3Dmol.js and py3Dmol Source Repository and Examples. GitHub. Retrieved November 13, 2026, from https://github.com/3dmol/3Dmol.js
- Berman, H. M., Westbrook, J., Feng, Z., Gilliland, G., Bhat, T. N., Weissig, H., Shindyalov, I. N., & Bourne, P. E. (2000). The Protein Data Bank. Nucleic Acids Research, 28(1), 235–242. https://doi.org/10.1093/nar/28.1.235. Retrieved November 13, 2026.
- Conda-Forge Community. (2026). py3dmol Feedstock: Conda package for py3Dmol. Conda-Forge. Retrieved November 13, 2026, from https://anaconda.org/conda-forge/py3dmol
Data: Structural Biology Molecular Visualization Software Architectural Specifications
Comparative matrix of leading computational structural biology visualization frameworks, compiling rendering engines, Jupyter notebook integration mechanisms, primary input file formats, surface calculation capabilities, programmatic export types, licensing, and primary research workflows based on peer-reviewed methods papers and official developer documentation.
Period covered: 2015/2026. Coverage: Global.
| Software Package | Primary Developer & Institution | Graphics Engine | Jupyter Integration Mode | Key Coordinate Formats | Surface Algorithms | Standalone Export Formats | Software License |
|---|---|---|---|---|---|---|---|
| py3Dmol | University of Pittsburgh (Koes Lab) | WebGL 1.0/2.0 via 3Dmol.js | Static HTML/JavaScript (Kernel-Free) | PDB, mmCIF, SDF, MOL2, XYZ, PQR, CUBE | VDW, MS, SAS, SES | HTML (write_html), base64 PNG (png()) | MIT / BSD 3-Clause |
| NGLView | ASBMB / NGL Development Team | WebGL via NGL.js | Bidirectional ipywidgets (Active Kernel Required) | PDB, mmCIF, GRO, TRR, XTC, DCD, MMTF | Molecular Surface, SAS, Gaussian Surface | PNG, animated GIF, MP4 | MIT License |
| Mol* (Molstar) | RCSB PDB, PDBe, CEITEC | WebGL2 / WebGPU via TypeScript Engine | WebComponent / molstar-python wrapper | mmCIF, BinaryCIF, PDB, SDF, CCP4, DSN6 | Molecular Surface, Gaussian Surface, ED Density | PNG, MP4, glTF 3D mesh, State JSON | MIT License |
| PyMOL Open-Source | Schrödinger, Inc. / Community | Desktop OpenGL (C/C++ native) | External window or IPyMOL static PNG | PDB, mmCIF, MOL, MOL2, SDF, CCP4, DX | Connolly, Solvent-Excluded, Gaussian, VDW | Ray-traced PNG, VRML, POV-Ray, OBJ, PSE | Open-Source (Python-style / BSD-like) |
| UCSF ChimeraX | UCSF Resource for Biocomputing (RBVI) | Desktop OpenGL 3.3+ via Qt GUI | External GUI or REST chimerax-web interface | PDB, mmCIF, MRC, CCP4, EM, BRIX, MTZ | Solvent-Excluded, Molecular, Density Meshes | High-res PNG, TIFF, MP4, VRML, GLTF, STL | Free for Academic / Non-Commercial |
| JSmol / Jmol | Jmol Development Team | HTML5 2D Canvas / WebGL (Java transpiled) | Via jupyter-jmol extension | PDB, CIF, MOL, XYZ, Gaussian, CUBE | Connolly, Molecular Surface, Isosurface | PNG, JPG, Jmol Script (.spt), HTML export | GNU LGPL v2.1 |
Sources
- 3Dmol.js: molecular visualization with WebGL (Bioinformatics) (accessed 2026-11-13)
- 3Dmol.js GLViewer API Reference and Documentation (accessed 2026-11-13)
- NGLView: An IPython/Jupyter widget to interactively view molecular structures and trajectories (Bioinformatics) (accessed 2026-11-13)
- Mol* Viewer: modern web app for 3D visualization and analysis of large biomolecular structures (Nucleic Acids Research) (accessed 2026-11-13)
- The PyMOL Molecular Graphics System, Version 2.0 (Schrodinger, LLC) (accessed 2026-11-13)
- UCSF ChimeraX: Meeting modern challenges in visualization and analysis (Protein Science) (accessed 2026-11-13)
- Jmol: an open-source Java viewer for chemical structures in 3D (accessed 2026-11-13)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







