How to open pymatgen json-files with nglview in Jupyter Notebook

You must have Python 3 and Jupyter Notebook already to be installed.

Let`s open your shell and execute next lines:

python3 -m pip install nglview
python3 -m pip install pymatgen
python3 -m pip install ase
jupyter-nbextension enable nglview --py
jupyter notebook

That was enough for me. Now let`s open browser with Jupyter and create new notebook with next code:

# Visualize pymatgen's structure with NGLView

import nglview
from pymatgen.core import Structure, Lattice
import numpy as np


def plot3d(structure, spacefill=True, show_axes=True):
    from itertools import product
    from pymatgen.core import Structure
    from pymatgen.core.sites import PeriodicSite
    eps = 1e-8
    sites = []
    for site in structure:
        species = site.species
        frac_coords = np.remainder(site.frac_coords, 1)
        for jimage in product([0, 1 - eps], repeat=3):
            new_frac_coords = frac_coords + np.array(jimage)
            if np.all(new_frac_coords < 1 + eps):
                new_site = PeriodicSite(species=species, coords=new_frac_coords, lattice=structure.lattice)
    structure_display = Structure.from_sites(sites)
    view = nglview.show_pymatgen(structure_display)
    if spacefill:
        view.add_spacefill(radius_type='vdw', radius=0.5, color_scheme='element')
    if show_axes:
        view.shape.add_arrow([-4, -4, -4], [0, -4, -4], [1, 0, 0], 0.5, "x-axis")
        view.shape.add_arrow([-4, -4, -4], [-4, 0, -4], [0, 1, 0], 0.5, "y-axis")
        view.shape.add_arrow([-4, -4, -4], [-4, -4, 0], [0, 0, 1], 0.5, "z-axis")
    = "perspective"
    return view

# HERE You need to select your pymatgen json file:


After running that You will see interactive nglviewer with structure from your file. В результате должен открыться просмотрщик молекулы nglview. You can scale it, rotate, whatever.

Good luck!

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam