### Setup and Dependencies
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Imports necessary libraries and initializes shared demo variables. Ensure pymatgen and ase are installed.
```python
"""Jupyter notebook demo for pymatviz widgets."""
# /// script
# dependencies = [
# "pymatgen>=2024.1.1",
# "ase>=3.22.0",
# "phonopy>=2.20.0",
# ]
# ///
# %%
import itertools
from typing import Final
import numpy as np
from ase.build import bulk, molecule
from ipywidgets import GridBox, Layout
from phonopy.structure.atoms import PhonopyAtoms
from pymatgen.analysis.phase_diagram import PDEntry, PhaseDiagram
from pymatgen.core import Composition, Lattice, Structure
import pymatviz as pmv
np_rng = np.random.default_rng(seed=0)
```
--------------------------------
### Install pymatviz and matminer
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_dielectric_eda.ipynb
Installs the necessary libraries for data loading and visualization. Run this command before importing the libraries.
```python
# matminer needed for loading data
!pip install pymatviz matminer
```
--------------------------------
### Install and Set Up Pre-commit Hooks
Source: https://github.com/janosh/pymatviz/blob/main/contributing.md
Install pre-commit and set up the hooks to ensure code quality and consistency before committing changes. This will automatically trigger linting and formatting checks.
```shell
pip install pre-commit
pre-commit install
git commit -m "commit message" # this will trigger the pre-commit hooks
```
--------------------------------
### Install pymatviz
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Install the pymatviz package using pip. Additional extras like 'brillouin' can be installed for specific functionalities.
```sh
pip install pymatviz
```
--------------------------------
### Install pymatviz and dash
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Installs the necessary libraries for creating interactive plots and accessing Materials Project data.
```python
# dash needed for interactive plots
!pip install pymatviz dash
```
--------------------------------
### Install pymatviz for Colab
Source: https://github.com/janosh/pymatviz/blob/main/examples/mp_bimodal_e_form.ipynb
Installs a specific version of pymatviz compatible with Python 3.7, recommended for Google Colab environments.
```sh
#!pip install pymatviz==0.5.1
```
--------------------------------
### Render ASE Atoms Structure in Jupyter
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Displays an ASE bulk structure using pymatviz's MIME auto-rendering. Ensure ASE is installed and imported.
```python
# %% ASE Atoms — auto-rendered via MIME type recognition
ose_atoms = bulk("Al", "fcc", a=4.05)
ose_atoms *= (2, 2, 2)
ose_atoms
```
--------------------------------
### Render PhonopyAtoms Structure in Jupyter
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Displays a PhonopyAtoms structure using pymatviz's MIME auto-rendering. Ensure Phonopy is installed and imported.
```python
# %% PhonopyAtoms — auto-rendered via MIME type recognition
PhonopyAtoms(
symbols=["Na", "Cl"],
positions=[[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]],
cell=[[4, 0, 0], [0, 4, 0], [0, 0, 4]],
)
```
--------------------------------
### Render ASE Molecule in Jupyter
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Displays a simple ASE molecule using pymatviz's MIME auto-rendering. Ensure ASE is installed and imported.
```python
# %% ASE molecule
ose_molecule = molecule("H2O")
ose_molecule.center(vacuum=3.0)
ose_molecule
```
--------------------------------
### Initialize CompositionWidget
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a CompositionWidget for interactive composition visualization in notebook environments.
```python
from pymatviz import CompositionWidget
from pymatgen.core import Composition
```
--------------------------------
### Initialize StructureWidget
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a StructureWidget for interactive 3D structure visualization in notebook environments.
```python
from pymatviz import StructureWidget
from pymatgen.core import Structure
```
--------------------------------
### Create Structure Widget
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a StructureWidget by loading a structure from a file.
```python
from pymatviz import StructureWidget
from pymatgen.core import Structure
structure = Structure.from_file("structure.cif")
struct_widget = StructureWidget(structure=structure)
```
--------------------------------
### Initialize TrajectoryWidget
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a TrajectoryWidget for interactive visualization of molecular dynamics trajectories in notebook environments.
```python
from pymatviz import TrajectoryWidget
```
--------------------------------
### Load and Display Band Structure Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Loads phonon band structure data from a fixture file and visualizes it using the BandStructureWidget. Requires `monty` and `pymatviz`. The widget displays band structure data with a specified height.
```python
import json
from monty.io import zopen
from monty.json import MontyDecoder
from pymatviz.utils.testing import TEST_FILES
import pymatviz as pmv
phonon_fixture_path = f"{TEST_FILES}/phonons/mp-2758-Sr4Se4-pbe.json.xz"
with zopen(phonon_fixture_path, mode="rt") as file:
phonon_doc = json.loads(file.read(), cls=MontyDecoder)
band_data = phonon_doc.phonon_bandstructure
pmv.BandStructureWidget(band_structure=band_data, style="height: 400px;")
```
--------------------------------
### Store and Load DataFrame
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Demonstrates how to use IPython's %store magic command to save a pandas DataFrame to disk and load it back later, avoiding repeated API calls.
```python
# uncomment line to cache large MP data
# %store df_mp
# uncomment line to load cached MP data from disk
%store -r df_mp
```
--------------------------------
### Load and Display DOS Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Loads phonon density of states (DOS) data from the same fixture document used for the band structure and visualizes it using the DosWidget. Requires `pymatviz`. The widget displays DOS data with a specified height.
```python
import pymatviz as pmv
# Assuming phonon_doc is loaded as in the BandStructureWidget example
# from monty.io import zopen
# from monty.json import MontyDecoder
# from pymatviz.utils.testing import TEST_FILES
# import json
# phonon_fixture_path = f"{TEST_FILES}/phonons/mp-2758-Sr4Se4-pbe.json.xz"
# with zopen(phonon_fixture_path, mode="rt") as file:
# phonon_doc = json.loads(file.read(), cls=MontyDecoder)
dos_data = phonon_doc.phonon_dos
pmv.DosWidget(dos=dos_data, style="height: 400px;")
```
--------------------------------
### Fetch All MP Formation Energies
Source: https://github.com/janosh/pymatviz/blob/main/examples/mp_bimodal_e_form.ipynb
Queries the Materials Project database for material IDs, formulas, and formation energies per atom. Requires a valid Materials Project API key.
```python
PMG_MAPI_KEY = "your Materials Project API key"
e_form_all_mp = MPRester(PMG_MAPI_KEY).query(
{}, ["material_id", "formula", "formation_energy_per_atom"]
)
df_e_form_all_mp = pd.DataFrame(e_form_all_mp).set_index("material_id")
```
--------------------------------
### Load Matbench Perovskite Dataset
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Loads the Matbench Perovskite dataset using the MPContribs library. This is the first step for any analysis.
```python
from mpcontribs.client import Client
client = Client()
df = client.get_contributions(
"ml", "matbench_perovskites", "latest", dataframe=True
)
print(df.head())
```
--------------------------------
### Convex Hull Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Visualizes a Li-Fe-O phase diagram, showing stable and unstable entries. Requires pymatgen for PhaseDiagram calculations.
```python
# %% Convex Hull — compute stability from PhaseDiagram entries
# Stable phases on the convex hull
stable_phases = {
"Li": -1.9,
"Fe": -4.2,
"O": -3.0,
"Li2O": -15.8,
"FeO": -13.0,
"Fe2O3": -33.0,
"Fe3O4": -46.0,
"LiFeO2": -25.0,
"Li5FeO4": -58.0,
"LiFe5O8": -92.0,
"Li2Fe2O4": -52.0,
"LiFeO3": -31.0,
"Li2FeO3": -37.0,
"LiFe2O4": -46.0,
"Li3FeO3": -42.0,
"Fe2O5": -40.0,
}
entries = [PDEntry(Composition(c), e) for c, e in stable_phases.items()]
_hull = PhaseDiagram(entries)
# Sweep Li_a Fe_b O_c compositions and place each above the hull with
# log-normal delta (median ~0.04 eV/atom, clamped to <=0.25 eV/atom for realism).
_seen = set(stable_phases)
for li_count, fe_count, o_count in itertools.product(range(7), range(7), range(1, 8)):
if li_count == 0 and fe_count == 0:
continue
comp = Composition({"Li": li_count, "Fe": fe_count, "O": o_count})
if comp.reduced_formula in _seen:
continue
_seen.add(comp.reduced_formula)
per_atom_delta = min(np_rng.lognormal(mean=-3.2, sigma=1.0), 0.25)
entries.append(
PDEntry(comp, _hull.get_hull_energy(comp) + per_atom_delta * comp.num_atoms)
)
phase_diag = PhaseDiagram(entries)
pmv.ConvexHullWidget(entries=phase_diag, style="height: 500px;")
```
--------------------------------
### Create Composition Widget
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a CompositionWidget with a Composition object.
```python
from pymatviz import CompositionWidget
from pymatgen.core import Composition
composition = Composition("Fe2O3")
comp_widget = CompositionWidget(composition=composition)
```
--------------------------------
### Create Composition Widgets Grid
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Displays a grid of CompositionWidgets comparing multiple compositions across pie, bar, and bubble display modes. Requires `pymatviz`, `itertools`, and `ipywidgets.Layout`. The grid layout is configured for columns and gaps.
```python
import itertools
from pymatgen import Composition
from ipywidgets import Layout, GridBox
import pymatviz as pmv
comps = (
"Fe2 O3",
Composition("Li P O4"),
dict(Co=20, Cr=20, Fe=20, Mn=20, Ni=20),
dict(Ti=20, Zr=20, Nb=20, Mo=20, V=20),
)
modes = ("pie", "bar", "bubble")
size = 100
children = [
pmv.CompositionWidget(
composition=comp,
mode=mode,
style=f"width: {(1 + (mode == 'bar')) * size}px; height: {size}px;",
)
for comp, mode in itertools.product(comps, modes)
]
layout = Layout(
grid_template_columns=f"repeat({len(modes)}, auto)",
grid_gap="2em 4em",
padding="2em",
)
GridBox(children=children, layout=layout)
```
--------------------------------
### Create and Display BandsAndDos Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Combines band structure and density of states into a single coordinated view using the BandsAndDosWidget. Requires `pymatviz` and pre-loaded band structure and DOS data. The widget displays both plots with a specified height.
```python
import pymatviz as pmv
# Assuming band_data and dos_data are loaded as in previous examples
# from monty.io import zopen
# from monty.json import MontyDecoder
# from pymatviz.utils.testing import TEST_FILES
# import json
# phonon_fixture_path = f"{TEST_FILES}/phonons/mp-2758-Sr4Se4-pbe.json.xz"
# with zopen(phonon_fixture_path, mode="rt") as file:
# phonon_doc = json.loads(file.read(), cls=MontyDecoder)
# band_data = phonon_doc.phonon_bandstructure
# dos_data = phonon_doc.phonon_dos
pmv.BandsAndDosWidget(band_structure=band_data, dos=dos_data, style="height: 500px;")
```
--------------------------------
### Build and Run Dash Application
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Sets up a Dash application with a Plotly graph and a dropdown to select compound arity. It defines a callback to update the graph's figure based on the dropdown selection and runs the app.
```python
app = dash.Dash(prevent_initial_callbacks=True)
graph = dash.dcc.Graph(figure=fig, id="ptable-heatmap", responsive=True)
dropdown = dash.dcc.Dropdown(
id="arity-dropdown",
options=[
dict(label=arity_label, value=arity_label)
for arity_label in elem_counts_by_arity
],
style=dict(width="15em", position="absolute", top="15%", left="30%"),
value="unary",
placeholder="Select arity",
)
main_layout = dash.html.Div([graph, dropdown], style=dict(fontFamily="sans-serif"))
app.layout = main_layout
@app.callback(Output(graph.id, "figure"), Input(dropdown.id, "value"))
def update_figure(dropdown_value: str) -> go.Figure:
"""Update figure based on dropdown value."""
return arity_figs[dropdown_value]
app.run(debug=True, mode="inline")
```
--------------------------------
### Fetch Available Fields from Materials Project API
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Retrieves and prints a comma-separated list of all available fields for materials data from the Materials Project API.
```python
print(", ".join(MPRester().materials.summary.available_fields))
```
--------------------------------
### Plot Formation Energy Distribution
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Creates a histogram to visualize the distribution of formation energies across the perovskites dataset. Includes a vertical line at 0 eV/atom for reference.
```python
import plotly.express as px
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
labels = {"e_form": "Formation Energy (eV/atom)"}
fig = px.histogram(df_perov, x="e_form", nbins=300, labels=labels)
title = "Matbench Perovskites Formation Energy Distribution"
fig.layout.title.update(text=title, x=0.5)
fig.layout.margin.update(b=10, l=10, r=10, t=40)
fig.add_vline(x=0, fillcolor="black", line=dict(width=2, dash="dot"))
```
--------------------------------
### Create Trajectory Widget with Structures
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a TrajectoryWidget with a list of structures.
```python
from pymatviz import TrajectoryWidget
trajectory1 = [struct1, struct2, struct3] # List of structures
traj_widget1 = TrajectoryWidget(trajectory=trajectory1)
```
--------------------------------
### Structure Widget: Wurtzite GaN
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Renders wurtzite GaN as an interactive 3D crystal structure with bonds. Uses pymatgen.core.Structure.
```python
# %% Structure Widget — wurtzite GaN (hexagonal, more interesting than cubic)
struct = Structure(
lattice=Lattice.hexagonal(3.19, 5.19),
species=["Ga", "Ga", "N", "N"],
coords=[
[1 / 3, 2 / 3, 0],
[2 / 3, 1 / 3, 0.5],
[1 / 3, 2 / 3, 0.375],
[2 / 3, 1 / 3, 0.875],
],
)
pmv.StructureWidget(structure=struct, show_bonds=True, style="height: 400px;")
```
--------------------------------
### Create and Display Trajectory Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Generates a trajectory with structure, energy, and force data, then visualizes it using the TrajectoryWidget. Requires `pymatviz`, `pymatgen`, and `numpy`. The widget displays structures and associated scatter data.
```python
from pymatgen.core import Lattice, Structure
import numpy as np
import pymatviz as pmv
trajectory = []
base_struct = Structure(
lattice=Lattice.cubic(3.0),
species=("Fe", "Fe"),
coords=((0, 0, 0), (0.5, 0.5, 0.5)),
)
for idx in range(n_steps := 20):
struct_frame = base_struct.perturb(distance=0.2).copy()
energy = n_steps / 2 - idx * np_rng.random()
np.fill_diagonal(dist_max := struct_frame.distance_matrix, np.inf)
trajectory.append(
{"structure": struct_frame, "energy": energy, "force_max": 1 / dist_max.min()}
)
pmv.TrajectoryWidget(
trajectory=trajectory,
display_mode="structure+scatter",
style="height: 600px;",
)
```
--------------------------------
### Brillouin Zone Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Displays the reciprocal-space Brillouin zone for the provided hexagonal GaN structure. Requires a pymatgen Structure object.
```python
# %% Brillouin Zone — hexagonal BZ from GaN
pmv.BrillouinZoneWidget(structure=struct, show_vectors=True, style="height: 400px;")
```
--------------------------------
### Search Materials Project Data
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Fetches summary data for materials, specifically requesting material ID, formula, and the number of elements. It uses a context manager for MPRester and sets `use_document_model=False`.
```python
PMG_MAPI_KEY = "your Materials Project API key"
with MPRester(use_document_model=False) as mpr:
mp_data = mpr.materials.summary.search(
# nelements=[4, None], # 4 or less elements
fields=[Key.mat_id, Key.formula, "nelements"]
)
```
--------------------------------
### Visualize 3D Structures
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Generates and displays an interactive 3D visualization of the first 12 crystal structures from the dataset.
```python
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
fig = pmv.structure_3d(df_perov[Key.structure].iloc[:12])
fig.layout.paper_bgcolor = "rgba(255, 255, 255, 0.5)"
fig.show()
```
--------------------------------
### Create Trajectory Widget with Dicts
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Instantiate a TrajectoryWidget with a list of dictionaries, where each dictionary contains a 'structure' and other properties like 'energy'.
```python
from pymatviz import TrajectoryWidget
trajectory2 = [{"structure": struct1, "energy": 1.0}, {"structure": struct2, "energy": 2.0}, {"structure": struct3, "energy": 3.0}] # dicts with "structure" and property values
traj_widget2 = TrajectoryWidget(trajectory=trajectory2)
```
--------------------------------
### Isosurface Rendering (CHGCAR)
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Loads a VASP CHGCAR file and renders charge density isosurfaces using StructureWidget. Configure isosurface value, opacity, and colors.
```python
# %% Isosurface — Si charge density from CHGCAR
matterviz_iso_dir_url: Final = (
"https://github.com/janosh/matterviz/raw/550d96d2/src/site/isosurfaces"
)
pmv.StructureWidget(
data_url=f"{matterviz_iso_dir_url}/Si-CHGCAR.gz",
isosurface_settings={
"isovalue": 0.05,
"opacity": 0.6,
"positive_color": "#3b82f6",
"show_negative": False,
},
style="height: 500px;",
)
```
--------------------------------
### Element Percentage Heatmap
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Generates a heatmap visualizing the percentage of different elements present in the perovskites dataset, excluding Oxygen.
```python
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
fig = pmv.ptable_heatmap_plotly(
df_perov[Key.formula], exclude_elements=["O"], heat_mode="percent"
)
title = "Elements in Matbench Perovskites dataset"
fig.layout.title.update(text=title, x=0.36, y=0.9)
fig.show()
```
--------------------------------
### Load and Process Perovskites Dataset
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Loads the Matbench Perovskites dataset and extracts key features such as spacegroup number, volume, formula, and crystal system.
```python
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
df_perov = load_dataset("matbench_perovskites")
moyo_spg_num_key = "moyopy_spg_num"
df_perov[moyo_spg_num_key] = [
struct.get_symmetry_dataset(backend="moyopy", return_raw_dataset=True).number
for struct in tqdm(df_perov[Key.structure])
]
df_perov[Key.volume] = df_perov[Key.structure].map(lambda struct: struct.volume)
df_perov[Key.formula] = df_perov[Key.structure].map(lambda cryst: cryst.formula)
df_perov[Key.crystal_system] = df_perov[moyo_spg_num_key].map(
pmv.utils.spg_to_crystal_sys
)
```
--------------------------------
### XRD Widget: Rutile TiO2
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Computes and displays an XRD pattern for rutile TiO2. Uses pymatgen.analysis.diffraction.xrd.XRDCalculator.
```python
# %% XRD Pattern — rutile TiO2 (tetragonal, richer peak pattern than cubic Si)
from pymatgen.analysis.diffraction.xrd import XRDCalculator
tio2_struct = Structure(
Lattice.tetragonal(4.594, 2.959),
["Ti", "Ti", "O", "O", "O", "O"],
[
[0, 0, 0],
[0.5, 0.5, 0.5],
[0.305, 0.305, 0],
[0.695, 0.695, 0],
[0.195, 0.805, 0.5],
[0.805, 0.195, 0.5],
],
)
xrd_pattern = XRDCalculator().get_pattern(tio2_struct)
pmv.XrdWidget(patterns=xrd_pattern, style="height: 350px;")
```
--------------------------------
### Structure Widget: Multi-Vector Comparison
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Compares per-atom forces from two methods (DFT vs MLFF) on the same GaN structure. Vectors are color-coded and can be toggled.
```python
# %% Multi-Vector — DFT vs MLFF force comparison on GaN
struct_multi_vec = struct.copy(
site_properties={
"force_DFT": [
[0.15, -0.08, 0.03],
[-0.12, 0.18, -0.06],
[0.03, 0.06, -0.22],
[-0.09, -0.03, 0.15],
],
"force_MLFF": [
[0.13, -0.07, 0.04],
[-0.11, 0.16, -0.05],
[0.02, 0.07, -0.20],
[-0.08, -0.04, 0.14],
],
}
)
pmv.StructureWidget(
structure=struct_multi_vec,
show_bonds=True,
vector_configs={
"force_DFT": {"color": "#e74c3c"},
"force_MLFF": {"color": "#3498db"},
},
vector_origin_gap=0.3,
style="height: 400px;",
)
```
--------------------------------
### Create and Display Histogram Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Overlays histograms to summarize value distributions of two trigonometric series using the HistogramWidget. Requires `pymatviz` and data from `ScatterPlotWidget`. The widget displays value distributions with a y-axis grid.
```python
import pymatviz as pmv
import numpy as np
# Assuming scatter_series is defined as in the ScatterPlotWidget example
scatter_series = [
dict(label="sin(x)", x=np.linspace(0, 6.0, 60), y=np.sin(np.linspace(0, 6.0, 60))),
dict(
label="cos(x)",
x=np.linspace(0, 6.0, 60),
y=np.cos(np.linspace(0, 6.0, 60)),
y_axis="y2",
),
]
histogram_series = [
{key: s[key] for key in ("label", "x", "y")} for s in scatter_series
]
pmv.HistogramWidget(
series=histogram_series,
bins=20,
mode="overlay",
x_axis={"label": "Value"},
y_axis={"label": "Count"},
style="height: 360px;",
)
```
--------------------------------
### Load Aflow Protostructure Labels
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Loads Aflow Wyckoff labels from a CSV file hosted online. This process can be time-consuming and is noted to have taken approximately 6 hours in a previous run.
```python
import pandas as pd
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
# originally generated with aviary calling out to Aflow CLI, takes ~6h when running
# uninterrupted. see https://github.com/CompRhys/aviary/blob/14b2ab204ec/aviary/wren/utils.py#L158
aflow_protostructure_key = "aflow_wyckoff"
df_perov[f"{Key.protostructure}_aflow"] = pd.read_csv(
# 2022-05-17-matbench_perovskites_aflow_labels.csv
"https://docs.google.com/spreadsheets/d/"
"1Mhk5t3Ac_aHOTWMjZ1DL4LtUBIB21nWt7oy2t3M-fQU/export?format=csv"
)[aflow_protostructure_key]
```
--------------------------------
### Create Pandas DataFrame from MP Data
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Converts the fetched Materials Project data into a pandas DataFrame and sets the 'material_id' as the index. Displays the first few rows of the DataFrame.
```python
df_mp = pd.DataFrame(map(dict, mp_data)).set_index("material_id") # ty: ignore[invalid-argument-type]
df_mp.head()
```
--------------------------------
### Formation Energy vs. Volume Scatter Plot
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Visualizes the relationship between formation energy and volume for perovskites, colored by spacegroup number.
```python
import plotly.express as px
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
moyo_spg_num_key = "moyopy_spg_num"
fig = px.scatter(df_perov, x="volume", y="e_form", color=moyo_spg_num_key)
fig.layout.title = dict(text="Matbench Perovskites Formation Energy vs. Volume", x=0.5)
fig.layout.coloraxis.colorbar.update(
orientation="h", y=0, x=1, xanchor="right", thickness=10, len=0.6
)
fig.layout.margin.update(b=10, l=10, r=10, t=40)
fig.show()
```
--------------------------------
### Import Libraries and Configure Plotly
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_dielectric_eda.ipynb
Imports essential libraries including Plotly for visualization, matminer for dataset loading, and pymatviz for plotting utilities. Configures Plotly renderers for local and GitHub compatibility.
```python
import plotly.express as px
import plotly.io as pio
from matminer.datasets import load_dataset
from tqdm import tqdm
import pymatviz as pmv
from pymatviz.enums import Key
__author__ = "Janosh Riebesell"
__date__ = "2022-03-19"
# make plotly figures render both locally and on GitHub.
# https://github.com/plotly/plotly.py/issues/931#issuecomment-2098209279
pio.renderers.default = "vscode+png"
```
--------------------------------
### Generate Element Pair Radial Distribution Functions for Multiple Structures
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates plots of radial distribution functions for element pairs, comparing multiple structures provided as a dictionary.
```python
from pymatviz.rdf.figures import element_pair_rdfs
element_pair_rdfs({"A": struct1, "B": struct2})
```
--------------------------------
### Periodic Table Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Displays a periodic table with a heatmap for specified values, such as atomic masses. Customize the color scale.
```python
# %% PeriodicTable — atomic mass heatmap
pmv.PeriodicTableWidget(
heatmap_values={
"H": 1.008,
"He": 4.003,
"Li": 6.941,
"Be": 9.012,
"B": 10.81,
"C": 12.01,
"N": 14.01,
"O": 16.00,
"F": 19.00,
"Ne": 20.18,
"Na": 22.99,
"Mg": 24.31,
"Al": 26.98,
"Si": 28.09,
"Fe": 55.85,
},
color_scale="interpolateViridis",
style="height: 400px;",
)
```
--------------------------------
### Compare Spglib and Aflow Crystal Systems with Sankey Diagram
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Visualizes the differences between crystal systems determined by Spglib and Aflow using a Sankey diagram. This comparison helps in understanding the consistency of crystallographic classifications between the two methods.
```python
import pandas as pd
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
fig = pmv.sankey_from_2_df_cols(df_perov, ["spglib_crys_sys", "aflow_crys_sys"])
title = "Spglib vs Aflow Crystal systems
for the Matbench Perovskites dataset"
fig.layout.title = dict(text=title, x=0.5)
fig.show()
```
--------------------------------
### Cache and Load MP Data
Source: https://github.com/janosh/pymatviz/blob/main/examples/mp_bimodal_e_form.ipynb
Provides commands to cache the fetched Materials Project formation energy data into a pandas DataFrame and to load it later.
```python
# cache MP data
# %store df_e_form_all_mp
# load cached MP data
%store -r df_e_form_all_mp
```
--------------------------------
### Generate 3D Brillouin Zone for Cubic Structure
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates a 3D visualization of the Brillouin zone for a given cubic crystal structure.
```python
from pymatviz.brillouin import brillouin_zone_3d
brillouin_zone_3d(cubic_struct)
```
--------------------------------
### Plot Histogram of MP Formation Energies
Source: https://github.com/janosh/pymatviz/blob/main/examples/mp_bimodal_e_form.ipynb
Generates a histogram of formation energies per atom for all entries in the Materials Project database. Highlights a specific energy value with a vertical line and annotation.
```python
labels = {"formation_energy_per_atom": "Formation energy [eV/atom]"}
fig = px.histogram(
df_e_form_all_mp,
x="formation_energy_per_atom",
nbins=200,
range_x=(-5, 3),
labels=labels,
)
e_form_valley = -1.35
fig.add_vline(e_form_valley, line=dict(color="orange", dash="dash"))
fig.add_annotation(
text=f"{e_form_valley} eV/atom",
x=e_form_valley - 1,
y=0.05,
yref="paper",
font=dict(size=14, color="orange"),
showarrow=False,
)
fig.update_layout(title=dict(text=f"All {len(df_e_form_all_mp):,} MP entries", x=0.5))
```
--------------------------------
### Load and Process Dielectric Dataset
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_dielectric_eda.ipynb
Loads the 'matbench_dielectric' dataset and extracts space group information (symbol and number) and crystal system for each structure. Uses tqdm for progress indication.
```python
df_diel = load_dataset("matbench_dielectric")
df_diel[[Key.spg_symbol, Key.spg_num]] = [
struct.get_space_group_info() for struct in tqdm(df_diel[Key.structure])
]
df_diel[Key.crystal_system] = df_diel[Key.spg_num].map(pmv.utils.spg_to_crystal_sys)
```
--------------------------------
### Generate 3D Brillouin Zone for Hexagonal Structure
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates a 3D visualization of the Brillouin zone for a given hexagonal crystal structure.
```python
from pymatviz.brillouin import brillouin_zone_3d
brillouin_zone_3d(hexagonal_struct)
```
--------------------------------
### Chemical Potential Diagram Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Visualizes stability regions in chemical potential space using ChemPotDiagramWidget. Define entries with their energies and compositions.
```python
# %% ChemPotDiagram — Li-Fe-O system
pmv.ChemPotDiagramWidget(
entries=[
{"name": "Li", "energy": -1.9, "composition": {"Li": 1}},
{"name": "Fe", "energy": -8.3, "composition": {"Fe": 1}},
{"name": "O2", "energy": -4.9, "composition": {"O": 1}},
{"name": "Li2O", "energy": -14.3, "composition": {"Li": 2, "O": 1}},
{"name": "Fe2O3", "energy": -25.0, "composition": {"Fe": 2, "O": 3}},
{"name": "LiFeO2", "energy": -17.5, "composition": {"Li": 1, "Fe": 1, "O": 2}},
],
style="height: 500px;",
)
```
--------------------------------
### Cluster and Visualize Compositions
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Visualize 2D or 3D relationships between compositions and properties using various embedding and dimensionality reduction techniques. Supports optional property coloring.
```python
import pymatviz as pmv
from pymatgen.core import Composition
compositions = ("Fe2O3", "Al2O3", "SiO2", "TiO2")
# Create embeddings
embeddings = pmv.cluster.composition.one_hot_encode(compositions)
comp_emb_map = dict(zip(compositions, embeddings, strict=True))
# Plot with optional property coloring
fig = pmv.cluster_compositions(
compositions=comp_emb_map,
properties=[1.0, 2.0, 3.0, 4.0], # Optional property values
prop_name="Property", # Optional property label
embedding_method="one-hot", # or "magpie", "matscholar_el", "megnet_el", etc.
projection_method="pca", # or "tsne", "umap", "isomap", "kernel_pca", etc.
show_chem_sys="shape", # works best for small number of compositions; "color" | "shape" | "color+shape" | None
n_components=2, # or 3 for 3D plots
)
fig.show()
```
--------------------------------
### Heatmap Matrix Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Visualizes element pair interaction strengths using HeatmapMatrixWidget. Specify x and y items, values, and color scale.
```python
# %% HeatmapMatrix — element pair interactions
elements = ["Fe", "O", "Li", "Mn"]
pmv.HeatmapMatrixWidget(
x_items=elements,
y_items=elements,
values=[
[1.0, 0.8, 0.3, 0.6],
[0.8, 1.0, 0.2, 0.5],
[0.3, 0.2, 1.0, 0.4],
[0.6, 0.5, 0.4, 1.0],
],
color_scale="interpolateBlues",
style="height: 400px;",
)
```
--------------------------------
### Generate Element Pair Radial Distribution Functions
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates plots of radial distribution functions for element pairs within a given Pymatgen structure.
```python
from pymatviz.rdf.figures import element_pair_rdfs
element_pair_rdfs(pmg_struct)
```
--------------------------------
### Import Libraries and Set Plotly Template
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Imports necessary libraries for data manipulation, plotting, and Matbench dataset loading. Sets the Plotly template to 'pymatviz_white' for consistent styling.
```python
import pandas as pd
import plotly.express as px
import plotly.io as pio
from matbench_discovery.structure.prototype import get_protostructure_label
from matminer.datasets import load_dataset
from tqdm import tqdm
import pymatviz as pmv
from pymatviz.enums import Key
pmv.set_plotly_template("pymatviz_white")
__author__ = "Janosh Riebesell"
__date__ = "2022-03-19"
```
--------------------------------
### Pymatviz Citation Information
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
BibTeX entry for citing the pymatviz software. Include this in your LaTeX documents when referencing the library.
```bibtex
@software{riebesell_pymatviz_2022,
title = {Pymatviz: visualization toolkit for materials informatics},
author = {Riebesell, Janosh and Yang, Haoyu and Goodall, Rhys and Baird, Sterling G.},
date = {2022-10-01},
year = {2022},
doi = {10.5281/zenodo.7486816},
url = {https://github.com/janosh/pymatviz},
note = {10.5281/zenodo.7486816 - https://github.com/janosh/pymatviz},
urldate = {2023-01-01}, % optional, replace with your date of access
version = {0.8.2}, % replace with the version you use
}
```
--------------------------------
### Extract Structural Features and Plot Element Heatmap
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_dielectric_eda.ipynb
Calculates the volume and formula for each structure in the dataset. Generates a logarithmic heatmap of element frequencies using pymatviz.
```python
df_diel[Key.volume] = df_diel[Key.structure].map(lambda cryst: cryst.volume)
df_diel[Key.formula] = df_diel[Key.structure].map(lambda cryst: cryst.formula)
fig = pmv.ptable_heatmap_plotly(pmv.count_elements(df_diel[Key.formula]), log=True)
fig.layout.title.update(text="Elements in Matbench Dielectric", font_size=20)
fig.show()
```
--------------------------------
### Crystal System Counts Bar Chart
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Displays a bar chart showing the frequency of each crystal system found in the perovskites dataset.
```python
import plotly.express as px
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
fig = px.bar(df_perov[Key.crystal_system].value_counts())
fig.layout.title.update(text="Crystal systems in Matbench Perovskites", x=0.5)
fig.layout.update(showlegend=False, margin_t=50)
fig.show()
```
--------------------------------
### Generate 3D Brillouin Zone for Monoclinic Structure
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates a 3D visualization of the Brillouin zone for a given monoclinic crystal structure.
```python
from pymatviz.brillouin import brillouin_zone_3d
brillouin_zone_3d(monoclinic_struct)
```
--------------------------------
### Compare Spglib and Aflow Spacegroups with Sankey Diagram
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Visualizes the differences between spacegroup numbers determined by Spglib and Aflow using a Sankey diagram. This highlights potential discrepancies in crystallographic analysis.
```python
import pandas as pd
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
moyo_spg_num_key = "moyopy_spg_num"
aflow_spg_num_key = "aflow_spg_num"
fig = pmv.sankey_from_2_df_cols(df_perov, [moyo_spg_num_key, aflow_spg_num_key])
title = "Spglib vs Aflow Spacegroups
for the Matbench Perovskites dataset"
fig.layout.title = dict(text=title, x=0.5)
fig.show()
# pmv.io.save_and_compress_svg(fig, "sankey-spglib-vs-aflow-spacegroups")
```
--------------------------------
### Generate 3D Brillouin Zone for Orthorhombic Structure
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates a 3D visualization of the Brillouin zone for a given orthorhombic crystal structure.
```python
from pymatviz.brillouin import brillouin_zone_3d
brillouin_zone_3d(orthorhombic_struct)
```
--------------------------------
### Molecular Orbital Isosurface
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Renders molecular orbital isosurfaces (e.g., HOMO) from a Gaussian .cube file using StructureWidget. Customize isosurface settings including positive and negative colors.
```python
# %% Isosurface — caffeine HOMO orbital
pmv.StructureWidget(
data_url=f"{matterviz_iso_dir_url}/caffeine-HOMO.cube.gz",
isosurface_settings={
"isovalue": 0.02,
"opacity": 0.7,
"positive_color": "#3b82f6",
"negative_color": "#ef4444",
"show_negative": True,
},
show_bonds=True,
style="height: 500px;",
)
```
--------------------------------
### Spacegroup Sunburst Chart
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Displays a sunburst chart illustrating the distribution of spacegroups within the perovskites dataset, with counts shown as percentages.
```python
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
moyo_spg_num_key = "moyopy_spg_num"
fig = pmv.spacegroup_sunburst(df_perov[moyo_spg_num_key], show_counts="percent")
fig.layout.title.update(text="Matbench Perovskites spacegroup sunburst", x=0.5)
fig.layout.margin.update(b=0, l=0, r=0, t=40)
fig.show()
```
--------------------------------
### Render Remote ASE Trajectory File
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Renders a trajectory file from a remote URL using TrajectoryWidget. Specify display mode, vector scale and color, and bonding strategy.
```python
# %% Render remote ASE trajectory file
matterviz_traj_dir_url: Final = (
"https://github.com/janosh/matterviz/raw/6288721042/src/site/trajectories"
)
file_name = "Cr0.25Fe0.25Co0.25Ni0.25-mace-omat-qha.xyz.gz"
pmv.TrajectoryWidget(
data_url=f"{matterviz_traj_dir_url}/{file_name}",
display_mode="structure+scatter",
vector_scale=0.5,
vector_color="#ff4444",
show_bonds=True,
bonding_strategy="nearest_neighbor",
style="height: 600px;",
)
```
--------------------------------
### Generate and Display Initial Heatmaps
Source: https://github.com/janosh/pymatviz/blob/main/examples/mprester_ptable.ipynb
Iterates through different arities, generates a Plotly heatmap for element distribution using `ptable_heatmap_plotly`, and sets a descriptive title for each figure.
```python
for arity_label, elem_counts in elem_counts_by_arity.items():
fig = pmv.ptable_heatmap_plotly(elem_counts, log=True)
n_compounds = compound_counts_by_arity[arity_label]
fig.layout.title = dict(
text=f"Element distribution of {n_compounds:,} {arity_label} compounds in "
"Materials Project",
fontsize=16,
)
```
--------------------------------
### Extract Protostructure Labels
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Extracts and counts the unique protostructure labels from the dataset using a defined function.
```python
from pymatgen.core import Structure
from matminer.datasets import load_dataset
from tqdm.auto import tqdm
import pymatviz as pmv
from pymatviz.utils import Key
def get_protostructure_label(structure):
# Placeholder for actual protostructure extraction logic
# This is a simplified example; a real implementation would be more complex.
return structure.composition.reduced_formula
df_perov[Key.protostructure_moyo] = df_perov[Key.structure].map(
get_protostructure_label
)
df_perov[Key.protostructure_moyo].value_counts()
```
--------------------------------
### Plot Confusion Matrix
Source: https://github.com/janosh/pymatviz/blob/main/readme.md
Generates a confusion matrix visualization. Use this to evaluate classification model performance.
```python
from pymatviz.classify import confusion_matrix
# Example usage:
# confusion_matrix(conf_mat, ...)
# confusion_matrix(y_true, y_pred, ...)
```
--------------------------------
### Import Libraries and Configure Plotly
Source: https://github.com/janosh/pymatviz/blob/main/examples/mp_bimodal_e_form.ipynb
Imports necessary libraries for data manipulation, plotting, and Materials Project data retrieval. Configures Plotly renderers for different environments.
```python
import pandas as pd
import plotly.express as px
import plotly.io as pio
from pymatgen.ext.matproj import MPRester
from pymatviz import count_elements, ptable_heatmap_plotly
__author__ = "Janosh Riebesell"
__date__ = "2022-08-11"
pio.templates.default = "plotly_white"
# Interactive plotly figures don't show up on GitHub.
# https://github.com/plotly/plotly.py/issues/931
# change renderer from "svg" to "notebook" to get hover tooltips back
# (but blank plots on GitHub!)
pio.renderers.default = "png"
```
--------------------------------
### RDF Plot Widget
Source: https://github.com/janosh/pymatviz/blob/main/examples/widgets/jupyter_demo.ipynb
Plots the radial distribution function computed on-the-fly from a structure using RdfPlotWidget. Specify structures, cutoff, and number of bins.
```python
# %% RdfPlot — GaN pair distribution
pmv.RdfPlotWidget(
structures=struct.as_dict(),
cutoff=10,
n_bins=80,
style="height: 400px;",
)
```
--------------------------------
### Set Plotly Renderer
Source: https://github.com/janosh/pymatviz/blob/main/examples/matbench_perovskites_eda.ipynb
Configures Plotly to render figures as PNGs, ensuring compatibility across different environments like local machines and GitHub.
```python
import plotly.io as pio
# make plotly figures render both locally and on GitHub.
# https://github.com/plotly/plotly.py/issues/931#issuecomment-2098209279
pio.renderers.default = "png"
```