API

module pymatviz.bar

spacegroup_bar(data: Sequence[int | float | str | Structure] | pd.Series, *, show_counts: bool=True, xticks: Literal['all', 'crys_sys_edges'] | int=20, show_empty_bins: bool=False, log: bool=False, **kwargs: Any) -> go.Figure

source

Plot a histogram of spacegroups shaded by crystal system using Plotly.

Args

  • data (Sequence[int | float | str | Structure] | pd.Series): Space group symbols, integral numbers (1-230), or pymatgen structures. All inputs use numerically ordered space group numbers as x-axis labels.
  • show_counts (bool, optional): Whether to count the number of items in each crystal system. Defaults to True.
  • xticks ("all" | "crys_sys_edges" | int, optional): Where to add x-ticks. An integer will add ticks below that number of tallest bars. Defaults to 20. "all" will show below all bars, "crys_sys_edges" only at the edge from one crystal system to another.
  • show_empty_bins (bool, optional): Whether to include a zero-height bar for every missing space group, for any input format. Defaults to False.
  • log (bool, optional): Whether to log scale the y-axis. Defaults to False.
  • **kwargs: Keywords passed to plotly.express.bar().

Returns go.Figure: Plotly Figure object.

Raises

  • ValueError: If data is empty.

module pymatviz.brillouin

brillouin_zone_3d(struct: AnyStructure | Sequence[AnyStructure] | Mapping[Any, AnyStructure], *, surface_kwargs: dict[str, Any] | None=None, edge_kwargs: dict[str, Any] | None=None, point_kwargs: dict[str, Any] | Literal[False] | None=None, label_kwargs: dict[str, Any] | None=None, path_kwargs: dict[str, Any] | Literal[False] | None=None, axes_vectors: dict[Literal['shaft', 'cone'], dict[str, Any]] | Literal[False] | None=None, n_cols: int=3, subplot_title: Callable[[AnyStructure, Hashable], str | dict[str, Any]] | Literal[False] | None=None) -> go.Figure

source

Generate a 3D plotly figure of the first Brillouin zone for given structure(s).

Args

  • struct (AnyStructure | Sequence[AnyStructure]): Structure(s) to plot.

    Surface styling

  • surface_kwargs (dict): Styling for BZ surfaces.
  • edge_kwargs (dict): Styling for BZ edges.

    High symmetry point styling

  • point_kwargs (dict | Literal[False]): Styling for high symmetry points.
  • label_kwargs (dict): Styling for point labels.

    High symmetry path styling

  • path_kwargs (dict | Literal[False]): Styling for paths. Set to False to disable plotting paths.

    Coordinate axes styling

  • axes_vectors (dict | False): Keywords for coordinate axes vectors. Split into 2 sub dicts axes_vectors={shaft: {...}, cone: {...}}. Use nested key shaft.len to control vector length. Set to False to disable axes plotting.

    Grid layout

  • n_cols (int): Number of columns for subplots. Defaults to 3.
  • subplot_title (Callable[[AnyStructure, Hashable], str | dict] | False, optional): Function to generate subplot titles. Defaults to lambda struct_i, idx: f"{idx}. {struct_i.formula} (spg={spg_num})". Set to False to hide all subplot titles.

Returns go.Figure: A plotly figure containing the first Brillouin zone(s)

module pymatviz.chem_env

get_cn_from_symbol(ce_symbol: str, symbol_cn_mapping: dict[str, int]) -> int

source

Extract coordination number from ChemEnv symbol.

Args

  • ce_symbol (str): ChemEnv symbol (e.g., 'T:4', 'O:6', 'M:8')
  • symbol_cn_mapping (dict[str, int]): Mapping from symbols to coordination numbers

Returns

  • int: Coordination number

classify_local_env_with_order_params(center: PeriodicSite, neighbors: Sequence[PeriodicSite]) -> str

source

Classify a site from its image-resolved CrystalNN neighbors.

collect_coord_envs_chemenv(structures: Iterable[Structure], *, chem_env_settings: dict[str, Any] | None=None, normalize: bool=False) -> list[dict[str, Any]]

source

Collect coordination environment counts using pymatgen's ChemEnv module.

Args

  • structures (Iterable[Structure]): Structures to analyze.
  • chem_env_settings (dict | None): Passed to LocalGeometryFinder .setup_parameters. Defaults to None.
  • normalize (bool): Normalize counts per structure. Defaults to False.

Returns list[dict]: One dict per (coord_num, chem_env_symbol) pair per structure with keys coord_num, chem_env_symbol, count.

collect_coord_envs_crystal_nn(structures: Iterable[Structure], *, normalize: bool=False) -> list[dict[str, Any]]

source

Collect coordination environment counts using CrystalNN + order params (faster than ChemEnv but less detailed geometric classification).

Args

  • structures (Iterable[Structure]): Structures to analyze.
  • normalize (bool): Normalize counts per structure. Defaults to False.

Returns list[dict]: One dict per site per structure with keys coord_num, chem_env_symbol, count.

chem_env_nodes(structures: PeriodicStructure | Sequence[PeriodicStructure], *, chem_env_settings: ChemEnvSettings, normalize: bool, max_coordination_numbers: int | None, max_environments: int | None, mode: Literal['other', 'drop']) -> list[dict[str, Any]]

source

Build coordination-number branches with environment counts as leaves.

Rank coordination numbers by their full counts before limiting environments per branch. Ties use coordination number and environment symbol respectively.

module pymatviz.classify.confusion_matrix

confusion_matrix(conf_mat: Sequence[Sequence[int]] | np.ndarray | None=None, *, y_true: Sequence[str | int] | np.ndarray | None=None, y_pred: Sequence[str | int] | np.ndarray | None=None, x_labels: tuple[str, ...] | None=None, y_labels: tuple[str, ...] | None=None, annotations: Sequence[Sequence[str]] | Callable[[int, int, float, float], str] | None=None, normalize: bool=True, colorscale: str='blues', float_fmt: str='', heatmap_kwargs: dict[str, Any] | None=None, metrics: dict[str, str | None] | Sequence[str] | set[str]=('Acc',), metrics_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Plot confusion matrix using plotly. Accepts either a pre-computed confusion matrix or raw class labels.

Args

  • conf_mat (np.ndarray | None): Pre-computed confusion matrix. If None, will be computed from y_true and y_pred
  • y_true (np.ndarray | None): True class labels
  • y_pred (np.ndarray | None): Predicted class labels
  • x_labels (tuple[str, ...] | None): Labels for x-axis (predicted). If None and using raw labels, will be inferred from unique values in y_true and y_pred
  • y_labels (tuple[str, ...] | None): Labels for y-axis (true). If None, same as x_labels
  • annotations (Sequence[Sequence[str]] | Callable | None): Custom cell annotations (indexed like the confusion matrix: rows = true classes, columns = predicted) or a callable that takes (count, total, row_pct, col_pct) and returns a string. If None, will use pretty-formatted values in conf_mat. The callable receives: - count: Raw count for this cell - total: Total count across all cells - row_pct: Row percentage (count/row_sum) - col_pct: Column percentage (count/col_sum)
  • normalize (bool): Whether to normalize values to percentages that sum to 100%
  • colorscale (str): Plotly colorscale name
  • float_fmt (str): Format string for floating point numbers in annotations
  • heatmap_kwargs (dict | None): Additional keywords for pymatviz.utils.plotting.annotated_heatmap()
  • metrics (dict[str, str | None] | Sequence[str]): Which metrics to display and their format strings. If not dict, uses float_fmt for all metrics. Defaults to ("Acc",). Available metrics: "Acc", "Prec", "Rec", "F1", "MCC" (Matthews correlation coefficient). Only "Acc" applies to multi-class problems.
  • metrics_kwargs (dict | None): Additional keywords for metrics annotation.

Use fig.layout.(x|y)axis.title = str to set axis titles.

Returns go.Figure: Plotly figure object

module pymatviz.classify.curves

roc_curve(targets: ArrayLike | str, probs_positive: Predictions, df: pd.DataFrame | None=None, *, no_skill: dict[str, Any] | Literal[False] | None=None, **kwargs: Any) -> go.Figure

source

Plot the receiver operating characteristic (ROC) curve using Plotly.

Args

  • targets (ArrayLike | str): Ground truth binary labels
  • probs_positive (Predictions): Either: - Predicted probabilities for positive class, or - dict of form {"name": probabilities}, or - dict of form {"name": {"probs_positive": np.array, **trace_kwargs}}
  • df (pd.DataFrame | None): Optional DataFrame containing targets and probs_positive columns
  • no_skill (dict[str, Any] | False): Options for the no-skill diagonal or False to hide it. Keys: "xs"/"ys" (line points), "line" (plotly line style) and "annotation" (plotly annotation dict labeling the line).
  • **kwargs: Additional keywords passed to fig.add_scatter()

Returns

  • Figure: Plotly figure object

precision_recall_curve(targets: ArrayLike | str, probs_positive: Predictions, df: pd.DataFrame | None=None, *, no_skill: dict[str, Any] | Literal[False] | None=None, **kwargs: Any) -> go.Figure

source

Plot the precision-recall curve using Plotly.

Args

  • targets (ArrayLike | str): Ground truth binary labels
  • probs_positive (Predictions): Either: - Predicted probabilities for positive class, or - dict of form {"name": probabilities}, or - dict of form {"name": {"probs_positive": np.array, **trace_kwargs}}
  • df (pd.DataFrame | None): Optional DataFrame containing targets and probs_positive columns
  • no_skill (dict[str, Any] | False): Options for no-skill baselines computed from each classifier's valid rows, or False to hide them. Identical baselines share a line. Keys: "line" (plotly line style) and "annotation" (plotly annotation dict labeling the line).
  • **kwargs: Additional keywords passed to fig.add_scatter()

Returns

  • Figure: Plotly figure object

module pymatviz.cluster.composition.embed

try_composition(composition: str | Composition) -> Composition

source

Try to convert a string or Composition to a Composition.

matminer_featurize(compositions: Sequence[str | Composition] | pd.Series, preset: MatminerElementPropertyPreset='magpie', *, normalize: bool=False, feature_subset: list[str] | None=None, n_jobs: int | None=1) -> np.ndarray

source

Apply matminer featurization to chemical formulas or compositions.

This uses matminer's ElementProperty featurizer with the specified preset, which includes physical and chemical properties of elements.

Args

  • compositions (Sequence[str] | Sequence[Composition] | pd.Series): chemical formulas as strings or pymatgen Composition objects.
  • preset (str): Matminer preset to use. Options: "magpie", "deml", "matminer", "matscholar_el", "megnet_el" (default: "magpie").
  • normalize (bool): If True, L2-normalize each feature vector (default: False). Magpie-style features mix units (e.g. kelvin and eV), so a row norm is dominated by the largest-magnitude ones (melting temperature) and divides every feature by it; column standardization in project_vectors already puts features on a common scale.
  • feature_subset (list[str] | None): List of specific features to use from the full feature set. If None (default), all available features will be used.
  • n_jobs (int | None): Number of jobs to run in parallel. Set to 1 to disable multiprocessing (default). Set to None to use all available cores.

Returns np.ndarray: Array of shape (n_compositions, n_features) with featurized compositions.

one_hot_encode(compositions: Sequence[str | Composition] | pd.Series, *, normalize: bool=True, elements: Sequence[str | Element] | None=None) -> np.ndarray

source

One-hot encode chemical formulas or compositions.

Args

  • compositions (Sequence[str] | Sequence[Composition] | pd.Series): chemical formulas as strings or pymatgen Composition objects.
  • normalize (bool): Whether to normalize the feature vectors to unit norm (default: True)
  • elements (Sequence[str | Element] | None): Elements to include in the one-hot encoding. If None (default), all elements in the periodic table will be used. Compositions with elements outside this list raise ValueError.

Returns np.ndarray: Array of shape (n_compositions, n_elements) with one-hot encoded compositions where each row corresponds to a composition and each column to an element's fraction in that composition.

module pymatviz.cluster.composition.plot

ClusterFigure

source

A Plotly Figure with typed metadata for clustering visualizations.

embeddings rows follow the plotted point order, i.e. sorted by property when cluster_compositions(sort=...) reorders the points, not df_in order.

ProjectionCallable

source

Protocol for custom projection functions.

EmbeddingCallable

source

Protocol for custom embedding functions.

EmbeddingMethod

source

Supported embedding methods for composition vectorization.

ProjectionMethod

source

Supported projection methods for dimensionality reduction.

cluster_compositions(df_in: pd.DataFrame, composition_col: str='composition', *, prop_name: str | None=None, embedding_method: str | EmbeddingMethod | EmbeddingCallable=EmbeddingMethod.magpie, projection: ProjectionMethod | ProjectionCallable | str, n_components: int=2, hover_format: str='.2f', heatmap_colorscale: str='Viridis', marker_size: int=8, show_chem_sys: ShowChemSys | None=None, color_discrete_map: Mapping[str, ColorType] | None=None, embedding_kwargs: dict[str, Any] | None=None, projection_kwargs: dict[str, Any] | None=None, sort: bool | int | Callable[[np.ndarray], np.ndarray]=True, show_projection_stats: bool | dict[str, Any]=True, color_scale: ColorScale | dict[str, Any]='linear', annotate_points: Callable[[pd.Series], str | dict[str, Any] | None] | None=None, **kwargs: Any) -> ClusterFigure

source

Plot chemical composition clusters with optional property coloring.

Gives a 2D or 3D scatter plot of chemical compositions, using various embedding and dimensionality reduction techniques to visualize the relationships between different materials.

Args

  • df_in (pd.DataFrame): DataFrame containing composition data and optionally properties and/or pre-computed embeddings.
  • composition_col (str): Name of the column containing one of: - Chemical formulas (as strings) - pymatgen Composition objects - Pre-computed embeddings (as numpy arrays or lists) Default is "composition".
  • prop_name (str | None): Name of the column to use for coloring points. If provided, the values in this column will be used to color the points. (default: None)
  • embedding_method (str | EmbeddingMethod | Callable[[list[str], Any], ndarray]): Method to convert compositions to vectors (default: "magpie"). Options: - "one-hot": One-hot encoding of element fractions - "magpie": Matminer's MagPie featurization - "deml": Matminer's DEML featurization - "matminer": Matminer's ElementProperty featurization - "matscholar_el": Matminer's Matscholar Element featurization - "megnet_el": Matminer's MEGNet Element featurization - Callable: Custom embedding function that takes (N, ) array of compositions and returns (N, D) array of values where D is the number of dimensions in the embedding space. - Column name in df: Name of column containing pre-computed embeddings. If using this option, the column must contain numpy arrays or lists. Ignored if composition_col contains pre-computed embeddings.
  • projection: Method to reduce embedding dimensionality or column name with pre-computed coordinates - "pca": Principal Component Analysis (linear) - "tsne": t-distributed Stochastic Neighbor Embedding (non-linear) - "umap": Uniform Manifold Approximation and Projection (non-linear) - "isomap": Isometric Feature Mapping (non-linear) - "kernel_pca": Kernel Principal Component Analysis (non-linear) - Callable: Custom projection function that takes (N, D) array of values and returns (N, n_components) projected array where n_components is 2 or 3 and D is the number of dimensions in the embedding space. - Column name in df: Name of column containing pre-computed coordinates. If using this option, the column must contain numpy arrays or lists of length equal to n_components.
  • n_components (int): Projection dimensions (2 or 3) (default: 2)
  • hover_format (str): Python format spec (as in format(value, spec), e.g. ".2f", ".3g", ",.1e") for projected coordinates and numeric property values in hover text. Non-numeric (categorical) property values are shown as-is. Raises ValueError for invalid specs like printf-style "%.2f". (default: ".2f")
  • heatmap_colorscale (str): Colorscale for continuous property values (default: "Viridis")
  • marker_size (int): Size of the scatter plot points (default: 8)
  • show_chem_sys (ShowChemSys | None): How to visualize chemical systems: - "color": Color points by chemical system (if no properties) - None: Don't use chemical system visualization - "shape": Use different marker shapes for different chemical systems (works best with ≤10 different chemical systems) - "color+shape": Use both colors and shapes to distinguish chemical systems (works best with ≤10 different chemical systems) (default: None)
  • color_discrete_map (dict[str, ColorType] | None): Optional mapping of chemical systems to colors (default: None)
  • embedding_kwargs (dict[str, Any] | None): Additional keyword arguments for the embedding function (default: None)
  • projection_kwargs (dict[str, Any] | None): Additional keyword arguments for the projection function (default: None)
  • sort (bool | int | Callable[[np.ndarray], np.ndarray]): Controls point sorting before plotting (default: True) - True or 1: Sort by prop values in ascending order (highest points plotted last) - False or 0: No sorting - -1: Sort by prop values in descending order (highest points plotted first) - Callable: Custom sorting function. Takes an array of values and returns sorted indices
  • show_projection_stats (bool | dict[str, Any]): Whether to show statistics about the projection (default: True) - True: Show default stats - False: Don't show stats - dict: Customize stats appearance with plotly annotation parameters For PCA, shows variance explained by each component For t-SNE, shows perplexity and learning rate For UMAP, shows n_neighbors and min_dist For Isomap, shows n_neighbors and metric For Kernel PCA, shows kernel type and parameters
  • color_scale (str | dict): Method for scaling property values for coloring points (default: "linear"): - "linear": Linear scale (default) - "log": Logarithmic scale for positive values - "arcsinh": Inverse hyperbolic sine scale, handles both large positive and negative values - dict: Custom scale configuration with required "type" key: - {"type": "arcsinh", "scale_factor": float}: Custom scale factor (default: 2) - {"type": "arcsinh", "lin_thresh": float, "lin_scale": float}: Custom linearity threshold and scale (for fine-tuning the transition between linear and logarithmic regions)
  • annotate_points (Callable[[pd.Series], str | dict[str, Any] | None] | None): Function to generate text annotations for each point. Takes a pandas Series representing a row in the input DataFrame with added rows for the projected coordinates (e.g., 'pca1', 'pca2'). Should return a string to use as label or a dict with valid keys for fig.add_annotation().
  • **kwargs: Passed to px.scatter or px.scatter_3d (depending on n_components)

Returns

  • ClusterFigure: Plotly figure object with typed metadata attributes: - fig.projector: Fitted projection object (PCA, TSNE, etc.) or None for custom projection functions - fig.embeddings: Embeddings used for projection

module pymatviz.cluster.composition.project

project_vectors(data: np.ndarray, *, method: ProjectionMethod | None=None, n_components: int=2, random_state: int | None=42, scale_data: bool=True, **kwargs: Any) -> tuple[np.ndarray, PCA | TSNE | Isomap | KernelPCA | Any]

source

Project high-dimensional data to lower dimensions using various methods.

Args

  • data (NDArray): Input data array of shape (n_samples, n_features)
  • method ("pca" | "tsne" | "umap" | "isomap" | "kernel_pca"): Projection method to use (see ProjectionMethod enum)
  • n_components (int): Projection dimensions (2 or 3) (default: 2)
  • random_state (int | None): Random seed for reproducibility
  • scale_data (bool): Whether to standardize input columns before projection and rescale the projected coordinates to zero mean and unit overall variance (one shared factor for all axes, so aspect ratios are kept)
  • **kwargs: Additional arguments passed to the projection method

Returns tuple[np.array, PCA | TSNE | Isomap | KernelPCA | Any]: A tuple containing: - Projected data array of shape (n_samples, n_components) - The fitted projection object (PCA, TSNE, UMAP, Isomap, or KernelPCA)

Raises

  • ValueError: If method is invalid or n_components is too small
  • ImportError: If UMAP is requested but not installed

module pymatviz.coordination.figures

coordination_hist(structures: AnyStructure | Mapping[str, AnyStructure] | Sequence[AnyStructure] | pd.Series, *, strategy: float | NearNeighbors | type[NearNeighbors]=3.0, split_mode: CnSplitMode | str=CnSplitMode.by_element, bar_mode: Literal['group', 'stack']='stack', hover_data: Sequence[str] | dict[str, str] | None=None, element_color_scheme: ElemColorScheme | dict[str, str]=ElemColorScheme.pastel, annotate_bars: bool | dict[str, Any]=False, bar_kwargs: dict[str, Any] | None=None, subplot_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Create a plotly histogram of coordination numbers for given structure(s).

Args

  • structures (AnyStructure | dict[str, AnyStructure] | Sequence[AnyStructure]): A single structure or a dictionary or sequence of structures.
  • strategy (float | NearNeighbors | type[NearNeighbors]): Neighbor-finding strategy. Can be one of: - float: Cutoff distance for neighbor search in Angstroms. - NearNeighbors: An instance of a NearNeighbors subclass. - Type[NearNeighbors]: A NearNeighbors subclass (will be instantiated). Defaults to 3.0 (Angstroms cutoff).
  • split_mode (CnSplitMode | str): How to split the data into subplots or color groups. Can be one of: "none": Single plot with all data. All elements of all structures (if multiple were passed) will be shown in the same plot. "by element": Split into subplots by element. Matching colors across subplots for different elements indicate those elements belong to the same structure. "by structure": Split into subplots by structure, i.e. each structure gets its own subplot with coordination numbers for all sites plotted in the same color. "by structure and element": Like "by structure", each structure gets its own subplot, but elements are colored differently within each structure.
  • bar_mode ("group" | "stack"): How to arrange bars at the same coordination number. Can be one of: "group": Bars are grouped side by side. "stack": Bars are stacked on top of each other.
  • hover_data (Sequence[str] | dict[str, str] | None): Sequence of keys or dict mapping keys to pretty labels for additional data to be shown in the hover tooltip. The keys must exist in the site properties or properties dict of the structure.
  • element_color_scheme (ElemColorScheme | dict[str, str]): Color scheme for elements. Can be "jmol", "vesta", or a custom dict.
  • annotate_bars (bool | dict[str, Any]): If True, annotate bars with element symbols when split_mode is 'by_element' or 'by_structure_and_element'. If a dict, used as keywords for bar annotations, e.g. {"font_size": 12, "font_color": "red"}.
  • bar_kwargs (dict[str, Any] | None): Dictionary of keyword arguments to customize bar appearance. These will be passed to go.Bar().
  • subplot_kwargs (dict[str, Any] | None): Additional keyword arguments to pass to make_subplots().

Returns go.Figure: A plotly Figure object containing the histogram.

coordination_vs_cutoff_line(structures: AnyStructure | Mapping[str, AnyStructure] | Sequence[AnyStructure] | pd.Series, *, strategy: tuple[float, float] | NearNeighbors | type[NearNeighbors]=(1, 5), num_points: int=50, element_color_scheme: ElemColorScheme | dict[str, str]=ElemColorScheme.jmol, subplot_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Create a plotly line plot of cumulative coordination numbers vs cutoff distance.

Args

  • structures (AnyStructure | dict[str, AnyStructure] | Sequence[AnyStructure]): A single structure or a dictionary or sequence of structures.
  • strategy (tuple[float, float] | NearNeighbors | type[NearNeighbors]): Neighbor-finding strategy. Can be one of: - tuple[float, float]: (min_cutoff, max_cutoff) range in Angstroms. - NearNeighbors: An instance of a NearNeighbors subclass. - Type[NearNeighbors]: A NearNeighbors subclass (will be instantiated). Defaults to (1, 5) Angstrom range.
  • num_points (int): Number of points to calculate between min and max cutoff.
  • element_color_scheme (ElemColorScheme | dict[str, str]): Color scheme for elements. Can be "jmol", "vesta", or a custom dict.
  • subplot_kwargs (dict[str, Any] | None): Additional keyword arguments to pass to make_subplots().

Returns A plotly Figure object containing the line plot.

module pymatviz.coordination.helpers

CnSplitMode

source

How to split the coordination number histogram into subplots.

create_hover_text(*, struct_key: Hashable, elem_symbol: str, cn: int, count: int, hover_data: dict[str, str], data: dict[str, Any], is_single_structure: bool) -> str

source

Create hover text for a single bar in the histogram.

normalize_get_neighbors(strategy: float | NearNeighbors | type[NearNeighbors]) -> Callable[[Site, Any], list[Any]]

source

Normalize get_neighbors function.

calculate_average_cn(structure: IStructure | IMolecule, element: str, get_neighbors: Callable[[Site, Any], list[Any]]) -> float

source

Calculate the average coordination number for a given element in a structure.

Args

  • structure (IStructure | IMolecule): A pymatgen structure-like object.
  • element (str): Element symbol to calculate average CN for.
  • get_neighbors (Callable[[Site, Any], list[Any]]): Function to get neighbors for a site.

Returns Average coordination number for the given element. Returns 0 if element is not present in the structure.

coordination_nums_in_structure(structure: Structure, strategy: float | NearNeighbors | type[NearNeighbors]=3.0, group_by: Literal['element', 'specie', 'site']='element') -> dict[str, list[int]]

source

Get coordination numbers (CN) for each element in a structure.

Args

  • structure (Structure): A pymatgen Structure object
  • strategy (float | NearNeighbors | type[NearNeighbors]): Neighbor-finding strategy. Can be one of: - float: Cutoff distance for neighbor search in Angstroms - NearNeighbors: An instance of a NearNeighbors subclass - Type[NearNeighbors]: A NearNeighbors subclass (will be instantiated) Defaults to 3.0 (Angstroms cutoff)
  • group_by ("element" | "specie" | "site"): How to group the coordination numbers. Can be one of: - "element": Group by element symbol - "site": Group by site - "specie": Group by specie

Returns dict[str, list[int]]: Map of element symbols to lists of coordination numbers. E.g. {"Si": [4, 4, 4], "O": [2, 2, 2, 2, 2, 2]} for SiO2. Each number represents the CN of one atom of that element.

Example >>> from pymatgen.core import Structure >>> structure = Structure.from_file("SiO2.cif") >>> cns = coordination_nums_in_structure(structure) >>> print(cns) {"Si": [4, 4, 4], "O": [2, 2, 2, 2, 2, 2]}

module pymatviz.data

RegressionData

source

Regression data containing: y_true, y_pred and y_std.

regression(n_samples: int=500, true_mean: float=5, true_std: float=4, pred_slope: float=1.2, pred_intercept: float=-2, seed: int=0) -> RegressionData

source

Generate dummy regression data for testing and prototyping.

This function creates synthetic data to simulate a regression task:

  • y_true: Sampled from a normal distribution with mean 5 and standard deviation 4.
  • y_pred: Linearly related to y_true with a slope of 1.2 and additional Gaussian noise.
  • y_std: Residuals scaled by random noise, representing variability in predictions.

Parameters

  • n_samples (int): Number of samples to generate. Default is 500.

Returns

  • RegressionData: A named tuple containing y_true, y_pred, and y_std.

module pymatviz.enums

LabelEnum

source

StrEnum with optional label and description attributes plus dict() methods.

Simply add label and description as a tuple starting with the key's value.

label() -> str

Make label read-only.

description() -> str

Make description read-only.

Key

source

Keys used to access dataframes columns, organized by semantic groups.

label() -> str

Label associated with the key.

unit() -> str | None

Unit associated with the key with HTML tags for sub/superscripts.

category() -> str

Category associated with the key.

symbol() -> str | None

Symbol associated with the key.

desc() -> str | None

Description associated with the key.

Task

source

What kind of task is being performed.

ElemCountMode

source

Mode of counting elements in a chemical formula.

ElemColorScheme

source

Names of element color palettes.

Used e.g. in structure visualizations and periodic table plots.

color_map() -> dict[str, ColorType]

Return map from element symbol to color.

SiteCoords

source

Site coordinate representations.

MetaFiles

source

Metaclass of Files enum that adds base_dir class kwarg.

Files

source

Enum of data files with associated file directories and URLs.

url() -> str

URL associated with the file.

file_path() -> str

File path associated with the file.

label() -> str

Label associated with the file.

description() -> str

Description associated with the file.

rel_path() -> str

Path of the file relative to the repo's ROOT directory.

from_label(cls, label: str) -> Self

Get enum member from pretty label.

module pymatviz.histogram

elements_hist(formulas: ElemValues, *, count_mode: ElemCountMode=ElemCountMode.composition, log_y: bool=False, keep_top: int | None=None, show_values: Literal['percent', 'count'] | None='percent', bar_width: float=0.7, opacity: float=0.8, fig_kwargs: dict[str, Any] | None=None, **kwargs: Any) -> go.Figure

source

Plot a histogram of elements (e.g. to show occurrence in a dataset) using Plotly.

Args

  • formulas (list[str]): compositional strings, e.g. ["Fe2O3", "Bi2Te3"].
  • count_mode ("composition" | "fractional_composition" | "reduced_composition"): Reduce or normalize compositions before counting. See count_elements for details. Only used when formulas is list of composition strings/objects.
  • log_y (bool, optional): Whether y-axis is log or linear. Default = False.
  • keep_top (int | None): Display only the top n elements by prevalence.
  • show_values ("percent"|"count"|None): "percent" (default) shows percentage labels on bars. "count" shows count values. None removes labels.
  • bar_width (float): Width of bars as fraction of available space. Default = 0.7.
  • opacity (float): Bar opacity between 0 and 1. Default = 0.8.
  • fig_kwargs (dict | None): Additional arguments passed to go.Figure().
  • **kwargs: Additional keyword arguments passed to go.Bar().

Returns go.Figure: Plotly figure object

histogram(values: Sequence[float] | np.ndarray | pd.Series | dict[str, Sequence[float] | np.ndarray | pd.Series], *, bins: int | Sequence[float] | str=200, x_range: tuple[float | None, float | None] | None=None, density: bool=False, bin_width: float=1.2, log_y: bool=False, fig_kwargs: dict[str, Any] | None=None, **kwargs: Any) -> go.Figure

source

Get a histogram using Plotly with fast numpy pre-processing.

Precompute bins with NumPy so rendering and HTML exports store bin counts instead of every input value.

Args

  • values: Values to plot as a histogram. Accepts a sequence, NumPy array, pandas Series, or dict of named series. Dict keys are used as legend labels.
  • bins (int or sequence, optional): The number of bins or the bin edges to use for the histogram. If not provided, a default value will be used.
  • x_range (tuple, optional): The range of values to include in the histogram. If not provided, the whole range of values will be used. Defaults to None.
  • density (bool, optional): Whether to normalize the histogram. Defaults to False.
  • bin_width (float, optional): The width of the histogram bins as a fraction of distance between bin edges. Defaults to 1.2 (20% overlap).
  • log_y (bool, optional): Whether to log scale the y-axis. Defaults to False.
  • fig_kwargs (dict, optional): Additional keywords passed to go.Figure().
  • **kwargs: Additional keyword arguments to pass to go.Figure.add_bar().

Returns go.Figure: The Plotly figure object containing the histogram.

module pymatviz.io

save_fig(fig: go.Figure, path: str, *, plotly_config: dict[str, Any] | None=None, style: str='', prec: int | None=None, template: str | None=None, **kwargs: Any) -> None

source

Write a plotly figure to disk (as HTML/PDF/SVG/...).

If the file has .svelte extension, insert {...$$props} into the figure's top-level div so it can be later styled and customized from Svelte code.

Args

  • fig (go.Figure): Plotly Figure object.
  • path (str): Path to image file that will be created.
  • plotly_config (dict, optional): Configuration options for fig.write_html(). Defaults to dict(showTips=False, responsive=True, modeBarButtonsToRemove= ["lasso2d", "select2d", "autoScale2d", "toImage"]). See https://plotly.com/python/configuration-options.
  • style (str, optional): CSS style string to be inserted into the HTML file. Defaults to "". Only used if path ends with .svelte or .html.
  • prec (int, optional): Number of decimal places to round trace x/y floats to in the exported file. Defaults to None (no rounding). Sensible values are usually 4, 5, 6.
  • template (str, optional): Temporary plotly to apply to the figure before saving. Will be reset to the original after. Defaults to "pymatviz_white" if path ends with .pdf or .pdfa, else None. Set to None to disable.
  • **kwargs: Keyword arguments passed to fig.write_html().

save_and_compress_svg(fig: go.Figure, filename: str) -> None

source

Save a Plotly figure as SVG to assets/svg/. Compresses SVG file with svgo CLI if available in PATH.

If filename does not include .svg extension and is not absolute, will be treated as relative to assets/ folder. This function is mostly meant for pymatviz internal use.

Args

  • fig (go.Figure): Plotly Figure instance.
  • filename (str): Name of SVG file (w/o extension).

Raises

  • TypeError: If fig is not a Plotly figure.

module pymatviz.notebook

notebook_mode(*, on: bool) -> None

source

Enable or disable pymatviz notebook display for pymatgen classes.

When enabled, pymatgen objects returned from notebook cells automatically render as interactive MatterViz widgets.

Works in Jupyter notebooks, JupyterLab, Marimo, VSCode interactive windows, and other notebook environments that support IPython display protocols.

Args

  • on: If True, enable automatic rendering. If False, restore prior display hooks.

module pymatviz.phonons.figures

phonon_bands(band_structs: AnyBandStructure | PhonopyBandStructure | Mapping[str, AnyBandStructure | PhonopyBandStructure], *, line_kwargs: dict[str, Any] | dict[Literal['acoustic', 'optical'], dict[str, Any]] | Callable[[np.ndarray, int], dict[str, Any]] | None=None, branches: Sequence[str]=(), path_mode: SetMode=SET_STRICT, shaded_ys: dict[tuple[YMin | YMax, YMin | YMax], dict[str, Any]] | bool | None=None, **kwargs: Any) -> go.Figure

source

Plot single or multiple pymatgen or phonopy band structures using Plotly.

Warning: Only tested with phonon band structures so far but plan is to extend to electronic band structures.

Args

  • band_structs (AnyBandStructure | dict[str, AnyBandStructure]): Single BandStructureSymmLine, PhononBandStructureSymmLine, or phonopy BandStructure object, or a dict with labels mapped to multiple such objects. If a dict, the keys are used as labels for the band structures.
  • line_kwargs (dict | dict[str, dict] | Callable): Line style configuration. Can be one of: - A single dict applied to all lines with Plotly line properties (e.g. dict(width=2, color="red", dash="solid")) - A dict with keys "acoustic" and "optical" containing style dicts for each mode type - A callable taking (frequencies: np.ndarray, band_idx: int) and returning a style dict Common style options include color, width, dash. Defaults to None.
  • branches (Sequence[str]): Branches to plot. Defaults to empty tuple, meaning all branches are plotted.
  • path_mode ("union" | "intersection" | "strict"): How to handle band structures with different q-point paths. Defaults to "strict": - "union": Plot all path segments from all band structures - "intersection": Only plot segments common to all band structures - "strict": Require matching branch order and repetitions (default)
  • shaded_ys (dict[tuple[float | str, float | str], dict]): Keys are y-ranges (min, max) tuple and values are kwargs for shaded regions created by fig.add_hrect(). Defaults to single entry (0, "y_min"): dict(fillcolor="gray", opacity=0.07). "y_min" and "y_max" will be replaced with the figure's y-axis range. dict(layer="below", row="all", col="all") is always passed to add_hrect but can be overridden by the user. Set to False to disable.
  • **kwargs: Passed to Plotly's Figure.add_scatter method.

Returns go.Figure: Plotly figure object.

Raises

  • TypeError: If band_structs is not a PhononBandStructureSymmLine, phonopy BandStructure or dict of these.

phonon_dos(doses: AnyDos | CompletePhononDos | Mapping[str, AnyDos | CompletePhononDos], *, stack: bool=False, sigma: float=0, units: Literal['THz', 'eV', 'meV', 'Ha', 'cm-1']='THz', normalize: Literal['max', 'sum', 'integral'] | None=None, last_peak_anno: str | None=None, project: Literal['element', 'site'] | None=None, show_total: bool=True, **kwargs: Any) -> go.Figure

source

Plot phonon DOS using Plotly.

Args

  • doses (AnyDos | CompletePhononDos | dict[str, AnyDos | CompletePhononDos]): pymatgen PhononDos, CompletePhononDos, phonopy TotalDos, or dict of these.
  • stack (bool): Whether to plot the DOS as a stacked area graph. Defaults to False.
  • sigma (float): Standard deviation for Gaussian smearing. Defaults to 0.
  • units (str): Units for the frequencies. Defaults to "THz".
  • normalize (str | None): Normalization mode. One of "max", "sum", "integral", or None. Defaults to None.
  • last_peak_anno (str): Annotation for last DOS peak with f-string placeholders for key (of dict containing multiple DOSes), last_peak frequency and units. Defaults to None, meaning last peak annotation is disabled. Set to "" to enable with a sensible default string.
  • project (str | None): Projection mode for CompletePhononDos. "element" decomposes into per-element partial DOS, "site" into per-site partial DOS. Requires CompletePhononDos input. Defaults to None (plot total DOS only).
  • show_total (bool): When projecting, overlay the total DOS as a dashed gray line. Only used when project is not None. Defaults to True.
  • **kwargs: Passed to Plotly's Figure.add_scatter method.

Returns go.Figure: Plotly figure object.

Raises

  • TypeError: If project is set but input is not CompletePhononDos.

convert_frequencies(frequencies: np.ndarray, unit: Literal['THz', 'eV', 'meV', 'Ha', 'cm-1']='THz') -> np.ndarray

source

Convert frequencies from THz to specified units.

Args

  • frequencies (np.ndarray): Frequencies in THz.
  • unit (str): Target units. One of 'THz', 'eV', 'meV', 'Ha', 'cm-1'.

Returns np.ndarray: Converted frequencies.

phonon_bands_and_dos(band_structs: PhononBands | Mapping[str, PhononBands], doses: PhononDos | Mapping[str, PhononDos], bands_kwargs: dict[str, Any] | None=None, dos_kwargs: dict[str, Any] | None=None, subplot_kwargs: dict[str, Any] | None=None, all_line_kwargs: dict[str, Any] | None=None, per_line_kwargs: dict[str, dict[str, Any]] | None=None, path_mode: SetMode=SET_STRICT, **kwargs: Any) -> go.Figure

source

Plot phonon DOS and band structure using Plotly.

Args

  • doses (PhononDos | dict[str, PhononDos]): PhononDos or dict of multiple.
  • band_structs (PhononBandStructureSymmLine | dict[str, PhononBandStructure]): Single BandStructureSymmLine or PhononBandStructureSymmLine object or a dict with labels mapped to multiple such objects.
  • bands_kwargs (dict[str, Any]): Passed to Plotly's Figure.add_scatter method.
  • dos_kwargs (dict[str, Any]): Passed to Plotly's Figure.add_scatter method.
  • subplot_kwargs (dict[str, Any]): Passed to Plotly's make_subplots method. Defaults to dict(shared_yaxes=True, column_widths=(0.8, 0.2), horizontal_spacing=0.03).
  • all_line_kwargs (dict[str, Any]): Passed to trace.update for each trace in fig.data. Modifies line appearance for all traces. Defaults to None.
  • per_line_kwargs (dict[str, str]): Map of line labels to kwargs for trace.update. Modifies line appearance for specific traces. Defaults to None.
  • path_mode (str): Mode for q-point path between band structures. Defaults to "strict". See phonon_bands for options.
  • **kwargs: Passed to Plotly's Figure.add_scatter method.

Returns go.Figure: Plotly figure object.

Raises

  • ValueError: If band_structs and doses keys don't match.

module pymatviz.phonons.helpers

PhononDBDoc

source

Dataclass for phonon DB docs.

from_dict(cls, data: dict[str, Any]) -> Self

Decode document fields, ignoring database metadata outside this schema.

pretty_sym_point(symbol: str) -> str

source

Convert a symbol to a pretty-printed version.

phonopy_to_pymatgen_bands(band_struct: PhonopyBandStructure) -> PhononBands

source

Convert phonopy BandStructure to pymatgen PhononBandStructureSymmLine.

Args

  • band_struct (PhonopyBandStructure): Phonopy band structure object

Returns

  • PhononBands: Converted pymatgen phonon band structure

module pymatviz.powerups

annotate_metrics(xs: ArrayLike | Sequence[ArrayLike], ys: ArrayLike | Sequence[ArrayLike], fig: go.Figure | None=None, metrics: Mapping[str, float | str] | Sequence[str]=('MAE', 'R2'), prefix: str='', suffix: str='', fmt: str='.3', **kwargs: Any) -> go.Figure

source

Provide a set of x and y values of equal length and an optional Figure object on which to print the values' mean absolute error and R^2 coefficient of determination.

Args

  • xs (array): x values. For faceted figures, either one array (or None to skip) per trace, or empty to use each trace's data.
  • ys (array): y values, same shape as xs.
  • fig (go.Figure | None, optional): plotly Figure on which to add the annotation. Defaults to None.
  • metrics (Mapping[str, float | str] | Sequence[str], optional): Metrics to show. A sequence of metric names (built-in MAE, RMSE, MSE, MAPE, R2, R2_adj or any sklearn.metrics function name) computed from xs and ys and labeled by name. A mapping of labels to either precomputed numbers (shown as is) or metric names (computed), e.g. {"Mean abs. error": "MAE", "Custom": 1.23}. Defaults to ("MAE", "R2").
  • prefix (str, optional): Title or other string to prepend to metrics. Defaults to "".
  • suffix (str, optional): Text to append after metrics. Defaults to "".
  • fmt (str, optional): f-string float format for metrics. Defaults to '.3'.
  • **kwargs: Additional arguments to pass to annotate().

Returns go.Figure: The annotated figure.

add_identity_line(fig: go.Figure, *, line_kwargs: dict[str, Any] | None=None, traces: TraceSelector=lambda _: True, retain_xy_limits: bool=False, **kwargs: Any) -> go.Figure

source

Add a y=x line shape to the background layer of a plotly figure spanning the overlap of the x and y ranges of the traces specified by traces.

Args

  • fig (go.Figure): plotly figure to add the identity line to.
  • line_kwargs (dict[str, Any], optional): Keyword arguments for customizing the line shape will be passed to fig.add_shape(line=line_kwargs). Defaults to dict(color="gray", width=1, dash="dash").
  • traces (TraceSelector, optional): Which trace(s) to use for determining the x/y range. Can be int, slice, sequence of ints, or a function that takes a trace and returns True/False. By default, applies to all traces.
  • retain_xy_limits (bool, optional): If True, the x/y-axis limits will be retained after adding the identity line. Defaults to False.
  • **kwargs: Additional arguments are passed to fig.add_shape().

Raises

  • TypeError: If fig is not a plotly figure.
  • ValueError: If fig is a plotly figure and no valid traces are found.

Returns go.Figure: Figure with added identity line.

add_best_fit_line(fig: go.Figure, *, xs: ArrayLike=(), ys: ArrayLike=(), traces: TraceSelector=lambda _: True, line_kwargs: dict[str, Any] | None=None, annotate_params: bool | dict[str, Any]=True, annotation_mode: AnnotationMode='per_trace', xref: str='x', yref: str='y', **kwargs: Any) -> go.Figure

source

Add line of best fit according to least squares to a plotly figure.

Args

  • fig (go.Figure): plotly figure to add the best fit line to.
  • xs (array, optional): x-values to use for fitting. Defaults to () which means use the x-values of traces selected by the traces parameter.
  • ys (array, optional): y-values to use for fitting. Defaults to () which means use the y-values of traces selected by the traces parameter.
  • traces (TraceSelector, optional): Which trace(s) to use. Can be int, slice, sequence of ints, or a function that takes a trace and returns True/False. By default, applies to all traces. Only used when xs and ys not provided.
  • line_kwargs (dict[str, Any], optional): Keyword arguments for customizing the line shape. Will be passed to fig.add_shape(line=line_kwargs). Defaults to None.
  • annotate_params (bool | dict[str, Any], optional): Pass dict to customize the annotation of the best fit line. Set to False to disable annotation. Defaults to True.
  • annotation_mode (AnnotationMode, optional): How to fit trace data. Options: - "per_trace": Each selected trace gets its own fit line and annotation - "combined": Selected traces in the same subplot share one fit line and annotation, replacing previous fit annotations - "none": Fit lines per trace without annotations Faceted figures get separate fits per subplot in all modes. Defaults to "per_trace".
  • xref (str, optional): x-axis of the subplot to draw directly passed xs/ys on, e.g. "x2". Defaults to "x".
  • yref (str, optional): y-axis matching xref, e.g. "y2". Defaults to "y".
  • **kwargs: Additional arguments are passed to fig.add_shape(). color sets the fit line color for directly passed xs/ys and traces without a color.

Raises

  • TypeError: If fig is not a plotly figure.
  • ValueError: If fig is a plotly figure and xs and ys are not provided and no valid traces are found.

Returns go.Figure: Figure with added best fit line.

enhance_parity_plot(fig: go.Figure | None=None, xs: ArrayLike=(), ys: ArrayLike=(), *, identity_line: bool | dict[str, Any]=True, best_fit_line: bool | dict[str, Any] | None=None, stats: bool | dict[str, Any] | None=True, traces: TraceSelector=lambda _: True, annotation_mode: AnnotationMode='combined') -> go.Figure | None

source

Add parity plot powerups to a plotly figure, including identity line (y=x), best-fit line, and pred vs ref statistics (MAE, R², ...).

Args

  • xs (array): x-values to use for fitting best-fit line and computing stats.
  • ys (array): y-values to use for fitting best-fit line and computing stats.
  • fig (go.Figure | None): plotly Figure to add powerups to. Defaults to None.
  • identity_line (bool | dict[str, Any], optional): Whether to add a parity line (y=x). Pass a dict to customize line properties. Defaults to True.
  • best_fit_line (bool | dict[str, Any] | None, optional): Whether to add a best-fit line. Pass a dict to customize line properties. If None (default), will be enabled if R² > 0.3.
  • stats (bool | dict[str, Any] | None, optional): Whether to display text box(es) with metrics (MAE, R², etc). Pass a dict to customize text box properties, or None to disable. Defaults to True.
  • traces (TraceSelector, optional): Specifies which trace(s) to use. Can be int, slice, sequence of ints, or a function that takes a trace and returns bool. By default, applies to all traces. Only used when xs and ys not provided.
  • annotation_mode (AnnotationMode, optional): How to display metric annotations. Defaults to "combined". Options: - "per_trace": Each selected trace gets its own annotation - "combined": All selected traces are combined into a single annotation - "none": Only add identity line and best-fit line, don't show annotations

Returns go.Figure: The enhanced figure.

Raises

  • ValueError: If xs and ys are not provided and fig is not a plotly figure where the data can be directly accessed.

add_ecdf_line(fig: go.Figure, values: ArrayLike=(), traces: TraceSelector=lambda _: True, trace_kwargs: dict[str, Any] | None=None, **kwargs: Any) -> go.Figure

source

Add an empirical cumulative distribution function (ECDF) line to a plotly figure.

Args

  • fig (go.Figure): plotly figure to add the ECDF line to.
  • values (array, optional): Values to compute the ECDF from. Defaults to () which means use the x-values of traces selected by the traces parameter.
  • traces (TraceSelector, optional): Specifies which trace(s) to use. Can be int, slice, sequence of ints, or a function that takes a trace and returns bool. By default, applies to all traces. Only used when values is not provided.
  • trace_kwargs (dict[str, Any], optional): Passed to trace_ecdf.update(). Defaults to None. Use e.g. to set trace name (default "Cumulative") or line_color (default "gray"). Applied to every added ECDF trace.
  • **kwargs: Passed to fig.add_trace().

Returns go.Figure: Figure with added ECDF line(s).

module pymatviz.process_data

count_elements(values: ElemValues, count_mode: ElemCountMode=ElemCountMode.composition, exclude_elements: str | Sequence[str]=(), fill_value: float | None=None) -> pd.Series

source

Count element occurrence in list of formula strings or dict-like compositions.

If passed values are already a map from element symbol to counts, ensure the data is a pd.Series filled with "fill_value" for missing element.

Provided as standalone function for external use or to cache long computations. Caching long element counts is done by refactoring: ptable_heatmap(long_list_of_formulas) # slow to elem_counts = count_elements(long_list_of_formulas) # slow ptable_heatmap(elem_counts) # fast, only rerun this line to update plot

Args

  • values (dict[str, int | float] | pd.Series | list[str]): Iterable of composition strings/objects or map from element symbols to heatmap values.
  • count_mode ('(element|fractional|reduced)_composition'): Only used when values is a list of composition strings/objects. - composition (default): Count elements in each composition as is, i.e. without reduction or normalization. - fractional_composition: Convert to normalized compositions in which the amounts of each species sum to one before counting. Example: Fe2 O3 -> Fe0.4 O0.6 - reduced_composition: Convert to reduced compositions (i.e. amounts normalized by greatest common denominator) before counting. Example: Fe4 P4 O16 -> Fe P O4. - occurrence: Count the number of times each element occurs in a list of formulas irrespective of compositions. E.g. [Fe2 O3, Fe O, Fe4 P4 O16] counts to {Fe: 3, O: 3, P: 1}.
  • exclude_elements (str | Sequence[str]): Element(s) to exclude from the count. Defaults to ().
  • fill_value (float | None): Value to fill in for missing elements. Defaults to None for NaN.

Returns pd.Series: Map element symbols to heatmap values.

count_formulas(data: Sequence[str | Composition | Structure], *, group_by: FormulaGroupBy='chem_sys') -> pd.DataFrame

source

Process chemical system data into a standardized DataFrame format.

Used e.g. by chem_sys_sunburst and chem_sys_treemap to preprocess input data.

Args

  • data (Sequence[str | Composition | Structure]): Chemical systems. Can be: - Chemical system strings like ["Fe-O", "Li-P-O"] - Formula strings like ["Fe2O3", "LiPO4"] - Pymatgen Compositions - Pymatgen Structures
  • group_by ("formula" | "reduced_formula" | "chem_sys"): How to group formulas: - "formula": Each unique formula is counted separately. - "reduced_formula": Formulas are reduced to simplest ratios. - "chem_sys": All formulas with same elements are grouped.

Returns pd.DataFrame: DataFrame with columns for arity, chemical system, and optionally formula, sorted by arity and chemical system for consistent ordering.

Raises

  • ValueError: If data is empty or contains invalid formulas/elements.
  • TypeError: If data contains unsupported types.

is_structure_like(obj: Any) -> bool

source

Whether obj is a pymatgen Structure/Molecule, ASE Atoms or PhonopyAtoms.

is_ase_atoms(struct: Any) -> TypeIs[Atoms]

source

Check if the input is an ASE Atoms object without importing ase.

is_phonopy_atoms(obj: Any) -> TypeIs[PhonopyAtoms]

source

Check if object is PhonopyAtoms or a subclass (Supercell, Primitive).

normalize_structures(systems: _StructureInputs) -> dict[Hashable, Structure | IStructure | Molecule | IMolecule]

source

Convert pymatgen Structures/IStructures, ASE Atoms, or PhonopyAtoms or sequences/dicts of them to a dictionary mapping hashable keys to pymatgen Structure-likes (Structure, IStructure, Molecule, and IMolecule).

Keys are derived from formulas for single structures, indices for sequences, or preserved from input dicts/Series.

normalize_periodic_structures(systems: _StructureInputs) -> dict[Hashable, IStructure]

source

Like normalize_structures but requires all inputs to be periodic.

Raises

  • TypeError: If any of the normalized structures is a (non-periodic) molecule.

df_to_arrays(df: pd.DataFrame | None, *args: str | ArrayLike, strict: bool=True) -> list[Any]

source

If df is None, this is a no-op: args are returned as-is. If df is a dataframe, all following args are used as column names and the column data returned as arrays (after dropping rows with NaNs in any column).

Args

  • df (pd.DataFrame | None): Optional pandas DataFrame.
  • *args (list[ArrayLike | str]): Arbitrary number of arrays or column names in df.
  • strict (bool, optional): If True, raise TypeError if df is not pd.DataFrame or None. If False, return args as-is. Defaults to True.

Raises

  • ValueError: If df is not None and any of the args is not a df column name.
  • TypeError: If df is not pd.DataFrame and not None.

Returns list[Any]: Array data for each column name, dictionary of column names and array data, or original string args when strict=False and df is not a DataFrame.

bin_df_cols(df_in: pd.DataFrame, bin_by_cols: Sequence[str], *, group_by_cols: Sequence[str]=(), n_bins: int | Sequence[int]=100, bin_counts_col: str='bin_counts', density_col: str='', verbose: bool=True) -> pd.DataFrame

source

Bin columns of a DataFrame.

Args

  • df_in (pd.DataFrame): Input dataframe to bin.
  • bin_by_cols (Sequence[str]): Columns to bin.
  • group_by_cols (Sequence[str]): Additional columns to group by. Defaults to ().
  • n_bins (int): Number of bins to use. Defaults to 100.
  • bin_counts_col (str): Column name for bin counts. Defaults to "bin_counts".
  • density_col (str): Column name for density values. Defaults to "".
  • verbose (bool): If True, report df length reduction. Defaults to True.

Returns pd.DataFrame: Binned DataFrame with original index name and values.

get_spacegroup_number(structure: AnyStructure) -> int

source

Determine an ordered periodic structure's space group without adapter extras.

normalize_spacegroups(data: Sequence[int | str | Any] | pd.Series) -> pd.Series

source

Normalize spacegroup data from structures, numbers, or symbols to a Series.

Handles pymatgen Structure, ASE Atoms, space group numbers (1-230), or Hermann-Mauguin symbols.

Args

  • data (Sequence[int | str | Structure] | pd.Series): Space group data. Can be: - Sequence of pymatgen Structures or ASE Atoms - Sequence of space group numbers (1-230) - Sequence of Hermann-Mauguin symbols - pandas Series of any of the above

Returns pd.Series: Integer space group numbers (1-230), preserving index and name.

Raises

  • ValueError: If data is empty, contains missing values, invalid symbols, or nonintegral/out-of-range space group numbers.

normalize_phonon_bands(band_structs: Any) -> dict[str, PhononBandStructureSymmLine]

source

Normalize phonon band structure input to a dict of pymatgen PhononBands.

Handles single or multiple band structures from pymatgen or phonopy.

Args

  • band_structs: Single band structure or dict/mapping of band structures. Can be: - pymatgen PhononBandStructureSymmLine - phonopy BandStructure - dict mapping labels to any of the above

Returns dict[str, PhononBandStructureSymmLine]: Dict mapping labels to pymatgen PhononBandStructureSymmLine objects.

Raises

  • TypeError: If input is not a supported band structure type.
  • ValueError: If input is an empty mapping.

sankey_flow_data(df: pd.DataFrame, cols: list[str], *, labels_with_counts: bool | str=True) -> dict[str, Any]

source

Extract flow data from DataFrame columns for Sankey diagrams.

Args

  • df (pd.DataFrame): DataFrame containing source and target columns.
  • cols (list[str]): 2-element list of [source_col, target_col] column names.
  • labels_with_counts (bool | "percent"): Whether to append counts to labels. If "percent", shows percentages instead of counts. Defaults to True.

Returns dict with keys: - "source": list of source node values - "target": list of target node values - "value": list of flow values (counts) - "labels": list of node labels (with optional counts) - "source_indices": list of source node indices for links - "target_indices": list of target node indices for links

Raises

  • ValueError: If cols doesn't have exactly 2 elements.

module pymatviz.ptable.figures

ptable_heatmap(values: ElemValues, *, count_mode: ElemCountMode=ElemCountMode.composition, colorscale: str | Sequence[str] | Sequence[tuple[float, str]]='viridis', show_scale: bool=True, show_values: bool=True, heat_mode: Literal['value', 'fraction', 'percent']='value', fmt: str | Callable[[float], str] | None=None, hover_props: Sequence[str] | dict[str, str] | None=None, hover_data: Mapping[str, str | int | float] | pd.Series | None=None, font_colors: Sequence[str]=(), gap: float=5, font_size: int | None=None, bg_color: str | None=None, nan_color: str='#eff', colorbar: dict[str, Any] | None=None, cscale_range: tuple[float | None, float | None]=(None, None), exclude_elements: Sequence[str]=(), log: bool=False, fill_value: float | None=None, element_symbol_map: dict[str, str] | None=None, label_map: dict[str, str] | Callable[[str], str] | Literal[False] | None=None, border: dict[str, Any] | Literal[False] | None=None, scale: float=1.0, **kwargs: Any) -> go.Figure

source

Create a Plotly figure with an interactive heatmap of the periodic table. Supports hover tooltips with custom data or atomic reference data like electronegativity, atomic_radius, etc. See kwargs hover_data and hover_props, resp.

Args

  • values (dict[str, int | float] | pd.Series | list[str]): Map from element symbols to heatmap values e.g. dict(Fe=2, O=3) or iterable of composition strings or Pymatgen composition objects.
  • count_mode ("composition" | "fractional_composition" | "reduced_composition"): Reduce or normalize compositions before counting. See count_elements for details. Only used when values is list of composition strings/objects.
  • colorscale (str | list[str] | list[tuple[float, str]]): Color scale for heatmap. Defaults to "viridis". See plotly.com/python/builtin-colorscales for names of other builtin color scales. Note "YlGn" and px.colors.sequential.YlGn are equivalent. Custom scales are specified as ["blue", "red"] or [[0, "rgb(0,0,255)"], [0.5, "rgb(0,255,0)"], [1, "rgb(255,0,0)"]].
  • show_scale (bool): Whether to show a bar for the color scale. Defaults to True.
  • show_values (bool): Whether to show numbers on heatmap tiles. Defaults to True.
  • heat_mode ("value" | "fraction" | "percent" | None): Whether to display heat values as is (value), normalized as a fraction of the total, as percentages or not at all (None). Defaults to "value". "fraction" and "percent" can be used to make the colors in different periodic table heatmap plots comparable.
  • fmt (str | Callable[[float], str] | None): f-string format option for heat labels. Defaults to ".1%" if heat_mode="percent" else ".1f".
  • hover_props (list[str] | dict[str, str]): Elemental properties to display in the hover tooltip. Can be a list of property names to display only the values themselves or a dict mapping names to what they should display as. E.g. dict(atomic_mass="atomic weight") will display as "atomic weight = {x}". Defaults to None. Available properties are: symbol, row, column, name, atomic_number, atomic_mass, n_neutrons, n_protons, n_electrons, period, group, phase, radioactive, natural, metal, nonmetal, metalloid, type, atomic_radius, electronegativity, first_ionization, density, melting_point, boiling_point, number_of_isotopes, discoverer, year, specific_heat, n_shells, n_valence.
  • hover_data (dict[str, str | int | float] | pd.Series): Map from element symbols to additional data to display in the hover tooltip. dict(Fe="this appears in the hover tooltip on a new line below the element name"). Defaults to None.
  • font_colors (list[str]): One color name or two for [min_color, max_color]. min_color is applied to annotations with heatmap values less than (max_val - min_val) / 2. Defaults to None, meaning auto-set to maximize contrast with color scale: white text for dark background and vice versa. swapped depending on the colorscale.
  • gap (float): Gap in pixels between tiles of the periodic table. Defaults to 5.
  • font_size (int): Element symbol and heat label text size. Any valid CSS size allowed. Defaults to automatic font size based on plot size. Element symbols will be bold and 1.5x this size.
  • bg_color (str): Plot background color. Defaults to "rgba(0, 0, 0, 0)".
  • colorbar (dict[str, Any]): Plotly colorbar properties documented at https://plotly.com/python/reference#heatmap-colorbar. Defaults to dict(orientation="h"). Commonly used keys are: - title: colorbar title - title_side: "top" | "bottom" | "right" | "left" - len: fraction of plot height or width depending on orientation When log=True, these keys have special handling: - tickvals: tick positions in LINEAR scale (auto log-transformed internally) - ticktext: custom tick labels (bypasses auto-generation if provided) - tickformat: Python format string for si_fmt(), e.g. ".2f" or ".3g" (NOTE: this is NOT Plotly's D3 tickformat syntax)
  • nan_color (str): Fill color for element tiles with NaN values. Defaults to "#eff".
  • cscale_range (tuple[float | None, float | None]): Colorbar range. Defaults to (None, None) meaning the range is automatically determined from the data.
  • exclude_elements (list[str]): Elements to exclude from the heatmap. E.g. if oxygen overpowers everything, you can do exclude_elements=["O"]. Defaults to ().
  • log (bool): Whether to use a logarithmic color scale. Defaults to False. Piece of advice: colorscale="viridis" and log=True go well together. Tick labels are auto-deduplicated by increasing precision if needed. Use colorbar={"tickformat": ".2f"} to control tick label precision.
  • fill_value (float | None): Value to fill in for missing elements. Defaults to 0.
  • element_symbol_map (dict[str, str] | None): A dictionary to map element symbols to custom strings. If provided, these custom strings will be displayed instead of the standard element symbols. Defaults to None.
  • label_map (dict[str, str] | Callable[[str], str] | None): Map heat values (after string formatting) to target strings. Set to False to disable. Defaults to dict.fromkeys((np.nan, None, "nan", "nan%"), "-") so as not to display "nan" for missing values.
  • border (dict[str, Any]): Border properties for element tiles. Defaults to dict(width=1, color="gray"). Other allowed keys are arguments of go.Heatmap which is (mis-)used to draw the borders as a 2nd heatmap below the main one. Pass False to disable borders.
  • scale (float): Scaling factor for whole figure layout. Defaults to 1.
  • **kwargs: Additional keyword arguments passed to pymatviz.utils.plotting.annotated_heatmap().

Returns

  • Figure: Plotly Figure object.

ptable_hists(data: pd.DataFrame | pd.Series | Mapping[str, Sequence[int | float] | np.ndarray[Any, Any]], *, bins: int=20, x_range: tuple[float | None, float | None] | None=None, log: bool=False, colorscale: str='RdBu', colorbar: dict[str, Any] | Literal[False] | None=None, hide_f_block: bool | Literal['auto']=False, font_size: int | None=None, scale: float=1.0, element_symbol_map: dict[str, str] | None=None, symbol_kwargs: dict[str, Any] | None=None, annotations: dict[str, str | dict[str, Any]] | Callable[[Sequence[float]], str | dict[str, Any] | list[dict[str, Any]]] | None=None, color_elem_strategy: ColorElemTypeStrategy='background', elem_type_colors: dict[str, str] | None=None, subplot_kwargs: dict[str, Any] | None=None, x_axis_kwargs: dict[str, Any] | None=None, y_axis_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Plotly figure with histograms for each element laid out in a periodic table.

Args

  • data (pd.DataFrame | pd.Series | dict[str, Sequence | ndarray]): Map from element symbols to histogram values. E.g. {"Fe": [1, 2, 3], "O": [4, 5]}. Values can be lists or numpy arrays. If pd.Series, index is element symbols and values lists. If pd.DataFrame, column names are element symbols and histograms are plotted from each column.

    --- Histogram-specific ---

  • bins (int): Number of bins for the histograms. Defaults to 20.

  • x_range (tuple[float | None, float | None]): x-axis range for all histograms. Defaults to None.

  • log (bool): Whether to log scale y-axis of each histogram. Defaults to False.

  • colorscale (str): Color scale for histogram bars. Defaults to "RdBu" (red to blue). See plotly.com/python/builtin-colorscales for other options.

  • colorbar (dict[str, Any] | None): Plotly colorbar properties. Defaults to dict(orientation="h"). See https://plotly.com/python/reference#heatmap-colorbar for available options. Set to False to hide the colorbar.

  • hide_f_block (bool | "auto"): Whether to hide the F-block elements. If "auto", hide F-block elements if row 7 is empty. Defaults to False.

    --- Layout ---

  • font_size (int): Element symbol and annotation text size. Defaults to automatic font size based on plot size.

  • scale (float): Scaling factor for whole figure layout. Defaults to 1.

    --- Text ---

  • element_symbol_map (dict[str, str] | None): A dictionary to map element symbols to custom strings. If provided, these custom strings will be displayed instead of the standard element symbols. Defaults to None.

  • symbol_kwargs (dict): Additional keyword arguments for element symbol text.

  • annotations (dict[str, str] | Callable[[np.ndarray], str] | None): Annotation to display for each element tile. Can be either: - dict mapping element symbols to annotation strings - callable that takes histogram values and returns annotation string - None for not displaying annotations (default)

    --- Element type colors ---

  • color_elem_strategy ("symbol" | "background" | "both" | "off"): Whether to color element symbols, tile backgrounds, or both based on element type. Defaults to "background".

  • elem_type_colors (dict | None): dict to map element types to colors. None to use the default = pymatviz.colors.ELEM_TYPE_COLORS.

  • subplot_kwargs (dict | None): Additional keywords passed to make_subplots(). Can be used e.g. to toggle shared x/y-axes.

  • x_axis_kwargs (dict | None): Additional keywords for x-axis like tickfont, showticklabels, nticks, tickformat, tickangle.

  • y_axis_kwargs (dict | None): Additional keywords for y-axis.

Returns go.Figure: Plotly Figure object with histograms in a periodic table layout.

ptable_heatmap_splits(data: pd.DataFrame | pd.Series | Mapping[str, Sequence[int | float] | np.ndarray[Any, Any]], *, orientation: PTableSplitOrientation='diagonal', colorscale: ColorScale | Sequence[ColorScale]='Viridis', colorbar: dict[str, Any] | Sequence[dict[str, Any]] | Literal[False] | None=None, on_empty: Literal['hide', 'show']='hide', hide_f_block: bool | Literal['auto']='auto', font_size: int | None=None, scale: float=1.0, element_symbol_map: dict[str, str] | None=None, symbol_kwargs: dict[str, Any] | None=None, annotations: dict[str, str | dict[str, Any]] | Callable[[np.ndarray], str | dict[str, Any]] | None=None, hover_template: str | None=None, hover_fmt: str | Callable[[float], str]='.3g', split_value_fmt: str | Sequence[str] | None='.3g', nan_color: str='#eff', zero_color: str='#aaa', hover_data: Mapping[str, str | int | float] | pd.Series | None=None, subplot_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Create a Plotly figure with an interactive heatmap of the periodic table, where each element tile is split into sections representing different values.

Args

  • data (pd.DataFrame | pd.Series | dict[str, Sequence | ndarray]): Map from element symbols to plot data. E.g. {"Fe": [1, 2], "Co": [3, 4]}, where the 1st value would be plotted in lower-left corner, 2nd in the upper-right. Values can be lists, tuples, or numpy arrays of numeric values.

    --- Figure ---

  • colorscale (ColorScale | Sequence[ColorScale]): Color scale(s) for heatmap. A single scale and colorbar share one value range across all splits. If a sequence is provided, each colorscale will be used for its corresponding split with an independent range. Can be: - str: Name of built-in colorscale ("turbo", "inferno", "plasma", ...) - list[str]: List of colors to interpolate between - list[tuple[float, str]]: List of (position, color) pairs - Callable[[str, float, int], str]: Function mapping (element symbol, split value, split index) to color string. Useful for custom color schemes.

  • colorbar (dict[str, Any] | Sequence[dict[str, Any]] | None): Plotly colorbar properties. If a single dict is provided, it will be used as a template for all colorbars. If a sequence is provided, each dict will be used for its corresponding split. Set to False to hide all colorbars. Defaults to dict(orientation="v"). Each colorbar dict can include any subset of plotly colorbar properties, see https://plotly.com/python/reference#heatmap-colorbar.

  • on_empty ("hide" | "show"): Whether to show tiles for elements without data. Defaults to "hide".

  • hide_f_block (bool | "auto"): Hide f-block (lanthanide and actinide series). Defaults to "auto", meaning hide if no data present. This keyword is slightly imprecisely named since it will hide the whole lanthanide and actinide rows even though the last items Lu + Lr in those rows are d-block.

  • orientation (str): How to split each element tile. Defaults to "diagonal". - "diagonal": Split at 45° angles - "horizontal": Split into equal horizontal strips - "vertical": Split into equal vertical strips - "grid": Split into 2x2 grid (only valid for n_splits=4)

    --- Layout ---

  • font_size (int): Element symbol and annotation text size. Defaults to automatic font size based on plot size.

  • scale (float): Scaling factor for whole figure layout. Defaults to 1.

    --- Symbol ---

  • element_symbol_map (dict[str, str] | None): A dictionary to map element symbols to custom strings. If provided, these custom strings will be displayed instead of the standard element symbols. Defaults to None.

  • symbol_kwargs (dict): Plotly annotation kwargs for the element symbol, centered in the tile by default. A "font" dict is merged into the default font (size font_size or 14, color contrasting with the tile). E.g. dict(y=0.8, font=dict(color="red", weight="bold")).

    --- Annotation ---

  • annotations (dict[str, str] | Callable[[np.ndarray], str] | None): Annotation to display for each element tile. Can be either: - dict mapping element symbols to annotation strings - callable that takes values and returns annotation string - None for not displaying annotations (default)

    --- Hover tooltip ---

  • hover_template (str | None): Custom template for hover tooltip. Use {name} for element name, {symbol} for element symbol, {split_name} for split name, {value} for split value, and {hover_data} for custom hover data. Defaults to None, which shows element name, symbol and all split values.

  • hover_fmt (str | Callable[[float], str]): Float format for values in hover tooltip. Can be either a format string (e.g. ".3g", ".2f") or a callable that takes a float value and returns a formatted string. Defaults to ".3g".

  • split_value_fmt (str | Sequence[str] | Literal[False] | None): Float format for split values in the heatmap. Can be: - str: Format string for all splits - Sequence[str]: Format strings for each split - None: Hide split values, i.e. no text labels on each tile split

    --- Additional options ---

  • nan_color (str): Color for NaN values. Defaults to "#eff".

  • zero_color (str): Color for zero values. Defaults to "#aaa".

  • hover_data (dict[str, str] | pd.Series): Additional text to append to hover tooltip for each element. Defaults to None.

  • subplot_kwargs (dict): Additional keyword arguments for subplots. See https://plotly.com/python/subplots/ for more information.

    For other args, see ptable_heatmap().

Returns go.Figure: Plotly Figure object with the periodic table heatmap splits.

Raises

  • ValueError: If n_splits not in {2, 3, 4} or orientation="grid" with n_splits!=4

ptable_scatter(data: Mapping[str, ElemData], *, mode: Literal['markers', 'lines', 'lines+markers']='markers', colorscale: str='viridis', colorbar: dict[str, Any] | Literal[False] | None=None, x_range: tuple[float | None, float | None] | None=None, y_range: tuple[float | None, float | None] | None=None, font_size: int | None=None, scale: float=1.0, hide_f_block: bool | Literal['auto']=False, element_symbol_map: dict[str, str] | None=None, symbol_kwargs: dict[str, Any] | None=None, marker_kwargs: dict[str, Any] | None=None, line_kwargs: dict[str, Any] | None=None, annotations: dict[str, str | dict[str, Any]] | Callable[[ElemData], str | dict[str, Any] | list[dict[str, Any]]] | None=None, color_elem_strategy: ColorElemTypeStrategy='symbol', elem_type_colors: dict[str, str] | None=None, subplot_kwargs: dict[str, Any] | None=None, x_axis_kwargs: dict[str, Any] | None=None, y_axis_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Create a Plotly figure with scatter/line plots for each element laid out in a periodic table.

Args

  • data (dict[str, ElemData]): Map from element symbols to either: 1. (x, y) or (x, y, color) data points for a single line/scatter plot E.g. {"Fe": ([1, 2, 3], [4, 5, 6])} plots points (1,4), (2,5), (3,6) 2. dict of (x, y) tuples for multiple lines per element E.g. {"Fe": {"line1": ([1, 2], [3, 4]), "line2": ([2, 3], [4, 5])}} In this case, a legend will be shown instead of a colorbar

  • mode ("markers" | "lines" | "lines+markers"): Plot mode. Defaults to "markers".

    --- Color settings ---

  • colorscale (str): Colorscale to use for numeric color data. Defaults to "viridis".

  • colorbar (dict | False | None): Colorbar settings. Defaults to None.

    --- Line-specific ---

  • x_range (tuple[float | None, float | None]): x-axis range for all line plots. Defaults to None, meaning auto-range.

  • y_range (tuple[float | None, float | None]): y-axis range for all line plots. Defaults to None, meaning auto-range.

    --- Layout ---

  • font_size (int): Element symbol and annotation text size. Defaults to automatic font size based on plot size.

  • scale (float): Scaling factor for whole figure layout. Defaults to 1.

  • hide_f_block (bool | "auto"): Whether to hide the F-block elements. If "auto", hide F-block elements if row 7 is empty. Defaults to False.

    --- Symbol ---

  • element_symbol_map (dict[str, str] | None): A dictionary to map element symbols to custom strings. If provided, these custom strings will be displayed instead of the standard element symbols. Defaults to None.

  • symbol_kwargs (dict): Plotly annotation kwargs for the element symbol, placed in the tile's top-right corner by default. E.g. dict(font=dict(size=16)).

    --- Annotation ---

  • annotations (dict[str, str] | Callable[[ElemData], str] | None): Annotation per element tile, see ptable_hists.

    --- Element type colors ---

  • color_elem_strategy ("symbol" | "background" | "both" | "off"): Whether to color element symbols, tile backgrounds, or both based on element type. Defaults to "symbol".

  • elem_type_colors (dict | None): dict to map element types to colors. None to use the default = pymatviz.colors.ELEM_TYPE_COLORS.

    --- Subplot ---

  • subplot_kwargs (dict | None): Additional keywords passed to make_subplots().

    --- Axis styling ---

  • x_axis_kwargs (dict | None): Additional keywords for x-axis like tickfont, showticklabels, nticks, tickformat, tickangle.

  • y_axis_kwargs (dict | None): Additional keywords for y-axis.

    --- Line/marker styling ---

  • line_kwargs (dict | None): Additional keywords for line plots like color, width, dash.

  • marker_kwargs (dict | None): Additional keywords for marker plots like color, size, symbol.

Returns go.Figure: Plotly Figure object with line plots in a periodic table layout.

module pymatviz.rainclouds

rainclouds(data: Mapping[str, Sequence[float] | np.ndarray | pd.Series | tuple[pd.DataFrame, str]], *, orientation: Literal['h', 'v']='h', alpha: float=0.7, width_viol: float=0.3, width_box: float=0.05, jitter: float=0.01, point_size: float=3, bw: float=0.2, cut: float=0.0, scale: Literal['area', 'count', 'width']='area', rain_offset: float=-0.25, offset: float | None=None, hover_data: Sequence[str] | Mapping[str, Sequence[str] | Mapping[str, Sequence[object]]] | None=None, show_violin: bool=True, show_box: bool=True, show_points: bool=True) -> go.Figure

source

Create a raincloud plot for multiple datasets using Plotly.

This plot type was proposed in https://wellcomeopenresearch.org/articles/4-63/v2. It is a vertical stack of:

  1. violin plot (the cloud)
  2. box plot (the umbrella)
  3. strip plot (the rain)

Args

  • data (dict[str, Union[Sequence[float], tuple[pd.DataFrame, str]]]): A dictionary where keys are labels and values are either sequences of float data or tuples containing a DataFrame and the column name to plot. Dataframes can hold additional columns to be used in hover tooltips.
  • orientation ("h" | "v", optional): Orientation of the plot. "h" for horizontal, "v" for vertical. Defaults to "h".
  • alpha (float, optional): Transparency of the violin plots. Defaults to 0.7.
  • width_viol (float, optional): Width of the violin plots. Defaults to 0.3.
  • width_box (float, optional): Width of the box plots. Defaults to 0.05.
  • jitter (float, optional): Amount of jitter for the strip plot. Defaults to 0.01.
  • point_size (float, optional): Size of the points in the strip plot. Defaults to 3.
  • bw (float, optional): Bandwidth for the KDE. Defaults to 0.2.
  • cut (float, optional): Distance past extreme data points to extend KDE. Defaults to 0.0.
  • scale ("area" | "count" | "width", optional): Method to scale the width of each violin. "area" normalizes by integral so all violins have equal area "count" scales by sample size, "width" normalizes by max so all violins have equal max width. Defaults to "area".
  • rain_offset (float, optional): Shift the strip plot position. Defaults to -0.25.
  • offset (float | None, optional): Shift the violin plot position. Defaults to None.
  • hover_data: Extra hover data. Pass None to show only plotted values. For DataFrame-backed data, pass column names like ["temperature", "pressure"], or a mapping from trace label to column names or per-point arrays, e.g. {"train": ["temperature"]} or {"train": {"source": ["DFT", "ML"]}}.
  • show_violin (bool, optional): Whether to show the violin plot. Defaults to True.
  • show_box (bool, optional): Whether to show the box plot. Defaults to True.
  • show_points (bool, optional): Whether to show the strip plot points. Defaults to True.

Returns go.Figure: The Plotly figure containing the raincloud plot.

module pymatviz.rdf.figures

element_pair_rdfs(structures: AnyStructure | Sequence[AnyStructure] | Mapping[str, AnyStructure] | pd.Series, cutoff: float | None=None, n_bins: int=75, bin_size: float | None=None, element_pairs: list[tuple[str, str]] | None=None, reference_line: dict[str, Any] | None=None, colors: Sequence[str] | None=None, line_styles: Sequence[str] | None=None, subplot_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Generate a plotly figure of pairwise radial distribution functions (RDFs) for all (or a subset of) element pairs in one or multiple structures.

Args

  • structures (AnyStructure | Sequence[AnyStructure] | dict[str, AnyStructure]): Can be one of the following: - single pymatgen Structure or ASE Atoms object - sequence (list, tuple) of pymatgen Structures or ASE Atoms objects - dictionary mapping labels to pymatgen Structures or ASE Atoms objects - pandas Series of pymatgen Structures or ASE Atoms objects
  • cutoff (float | None, optional): Maximum distance for RDF calculation. If None, defaults to twice the longest lattice vector length across all structures (up to 15A). If negative, its absolute value is used as a scaling factor for the longest lattice vector length (e.g. -1.5 means 1.5x the longest lattice vector). Default is None.
  • n_bins (int, optional): Number of bins for RDF calculation. Default is 75.
  • bin_size (float, optional): Size of bins for RDF calculation. If specified, it overrides n_bins. Default is None.
  • element_pairs (list[tuple[str, str]], optional): Element pairs to plot. If None, all pairs present in any structure are plotted.
  • reference_line (dict, optional): Keywords for reference line at g(r)=1 drawn with Figure.add_hline(). If None (default), no reference line is drawn.
  • colors (Sequence[str], optional): colors for each structure's RDF line. Defaults to plotly.colors.qualitative.Plotly.
  • line_styles (Sequence[str], optional): line styles for each structure's RDF line. Will be used for all element pairs present in that structure. Defaults to ["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"].
  • subplot_kwargs (dict, optional): Passed to plotly.make_subplots. Use this to e.g. set subplot_titles, rows/cols or row/column spacing to customize the subplot layout.

Returns go.Figure: A plotly figure with facets for each pairwise RDF, comparing one or multiple structures.

Raises

  • ValueError: If no structures are provided, if structures have no sites, if invalid element pairs are provided, or if both n_bins and bin_size are specified.
  • TypeError: If input structures are not pymatgen Structures or ASE Atoms.

full_rdf(structures: AnyStructure | Sequence[AnyStructure] | Mapping[str, AnyStructure] | pd.Series, cutoff: float=15, n_bins: int=75, bin_size: float | None=None, reference_line: dict[str, Any] | None=None, colors: Sequence[str] | None=None, line_styles: Sequence[str] | None=None) -> go.Figure

source

Generate a plotly figure of full radial distribution functions (RDFs) for one or multiple structures.

Args

  • structures (AnyStructure | Sequence[AnyStructure] | dict[str, AnyStructure]): Can be one of the following: - single pymatgen Structure or ASE Atoms object - list of pymatgen Structures or ASE Atoms objects - dictionary mapping labels to pymatgen Structures or ASE Atoms objects.
  • cutoff (float, optional): Maximum distance for RDF calculation. Default is 15 Å.
  • n_bins (int, optional): Number of bins for RDF calculation. Default is 75.
  • bin_size (float, optional): Size of bins for RDF calculation. If specified, it overrides n_bins. Default is None.
  • reference_line (dict, optional): Keywords for reference line at g(r)=1 drawn with Figure.add_hline(). If None (default), no reference line is drawn.
  • colors (Sequence[str], optional): colors for each structure's RDF line. Defaults to plotly.colors.qualitative.Plotly.
  • line_styles (Sequence[str], optional): line styles for each structure's RDF line. Defaults to ["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"].

Returns go.Figure: A plotly figure with full RDFs for one or multiple structures.

Raises

  • ValueError: If no structures are provided, if structures have no sites, or if both n_bins and bin_size are specified.

module pymatviz.rdf.helpers

calculate_rdf(structure: AnyStructure, center_species: str | None=None, neighbor_species: str | None=None, cutoff: float=15, n_bins: int=75, pbc: tuple[Literal[0, 1], Literal[0, 1], Literal[0, 1]]=(1, 1, 1)) -> tuple[np.ndarray, np.ndarray]

source

Calculate the radial distribution function (RDF) for a given structure.

If center_species and neighbor_species are provided, calculates the partial RDF for the specified element pair. Otherwise, calculates the full RDF.

Args

  • structure (AnyStructure): A periodic pymatgen Structure/IStructure, ASE Atoms, or PhonopyAtoms object (or mapping/sequence thereof).
  • center_species (str, optional): Symbol of the central species. If None, all species are considered.
  • neighbor_species (str, optional): Symbol of the neighbor species. If None, all species are considered.
  • cutoff (float, optional): Maximum distance for RDF calculation. Default is 15 Å.
  • n_bins (int, optional): Number of bins for RDF calculation. Default is 75.
  • pbc (tuple[int, int, int], optional): Periodic boundary conditions as any 3-tuple of 0s/1s. Defaults to (1, 1, 1).

Returns tuple[np.ndarray, np.ndarray]: Arrays of (radii, g(r)) values.

Raises

  • ValueError: If cutoff is not positive and finite, n_bins is not a positive integer, or pbc does not contain three 0/1 flags.
  • TypeError: If structure is unsupported or not periodic (e.g. a Molecule).

module pymatviz.sankey

sankey_from_2_df_cols(df: pd.DataFrame, cols: list[str], *, labels_with_counts: bool | Literal['percent']=True, annotate_columns: bool | dict[str, Any]=True, **kwargs: Any) -> go.Figure

source

Plot two columns of a dataframe as a Plotly Sankey diagram.

Args

  • df (pd.DataFrame): Pandas dataframe.
  • cols (list[str]): 2-tuple of source and target column names. Source corresponds to left, target to right side of the diagram.
  • labels_with_counts (bool, optional): Whether to append value counts to node labels. Defaults to True.
  • annotate_columns (bool, dict[str, Any], optional): Whether to use the column names as annotations vertically centered on the left and right sides of the diagram. If a dict, passed as **kwargs to plotly.graph_objects.Figure.add_annotation. Defaults to True.
  • **kwargs: Additional keyword arguments passed to plotly.graph_objects.Sankey.

Raises

  • ValueError: If len(cols) != 2.

Returns

  • Figure: Plotly figure containing the Sankey diagram.

module pymatviz.scatter

density_scatter(x: ArrayLike | str, y: ArrayLike | str, *, df: pd.DataFrame | None=None, density: Literal['kde', 'empirical'] | None=None, log_density: bool | None=None, n_bins: int | Literal[False] | None=None, bin_counts_col: str | None=None, xlabel: str | None=None, ylabel: str | None=None, identity_line: bool | dict[str, Any]=True, best_fit_line: bool | dict[str, Any]=True, stats: bool | dict[str, Any]=True, colorbar_kwargs: dict[str, Any] | None=None, hover_format: str='.3f', facet_col: str | None=None, **kwargs: Any) -> go.Figure

source

Scatter plot colored by density using Plotly.

This function uses binning to reduce the number of points plotted which enables plotting millions of data points and reduced file size for interactive plots.

Args

  • x (array | str): x-values or dataframe column name.
  • y (array | str): y-values or dataframe column name.
  • df (pd.DataFrame, optional): DataFrame with x and y columns. Defaults to None.
  • density ('kde' | 'empirical'): Determines the method for calculating and displaying density. Default is 'empirical' when n_bins is provided, else 'kde' for kernel density estimation.
  • log_density (bool | None): Whether to apply logarithmic scaling to density. If None, automatically set based on density range.
  • n_bins (int | None | False, optional): Number of bins for histogram. If None, automatically enables binning mode if the number of datapoints exceeds 1000, else defaults to False (no binning).
  • bin_counts_col (str, optional): Column name for bin counts. Defaults to "Point
    Density". Will be used as color bar title.
  • xlabel (str, optional): x-axis label. Auto-detected from data if None.
  • ylabel (str, optional): y-axis label. Auto-detected from data if None.
  • identity_line (bool | dict[str, Any], optional): Whether to add a parity line (y = x). Defaults to True. Pass a dict to customize line properties.
  • best_fit_line (bool | dict[str, Any], optional): Whether to add a best-fit line. Defaults to True. Pass a dict to customize line properties.
  • stats (bool | dict[str, Any], optional): Whether to display a text box with MAE and R^2. Defaults to True. Can be dict to pass kwargs to annotate_metrics().
  • colorbar_kwargs (dict, optional): Passed to fig.layout.coloraxis.colorbar.
  • hover_format (str, optional): Format specifier for the point density values.
  • facet_col (str | None, optional): Column name to use for creating faceted subplots. If provided, the plot will be split into multiple subplots based on unique values in this column. Defaults to None.
  • **kwargs: Passed to px.scatter().

Returns go.Figure: The plot object.

density_hexbin(x: ArrayLike | str, y: ArrayLike | str, *, df: pd.DataFrame | None=None, weights: ArrayLike | None=None, gridsize: int=75, identity_line: bool | dict[str, Any]=True, best_fit_line: bool | dict[str, Any]=True, stats: bool | dict[str, Any]=True, xlabel: str | None=None, ylabel: str | None=None, colorbar_kwargs: dict[str, Any] | None=None, **kwargs: Any) -> go.Figure

source

Hexagonal-grid scatter plot colored by point density using Plotly.

Args

  • x (array | str): x-values or dataframe column name.
  • y (array | str): y-values or dataframe column name.
  • df (pd.DataFrame, optional): DataFrame with x and y columns. Defaults to None.
  • weights (array, optional): If given, these values are accumulated in the bins. Otherwise, every point has value 1. Must be of the same length as x and y.
  • gridsize (int, optional): Grid intervals along each axis, with a second lattice offset by half an interval. Defaults to 75.
  • identity_line (bool | dict[str, Any], optional): Whether to add a parity line (y = x). Defaults to True. Pass a dict to customize line properties.
  • best_fit_line (bool | dict[str, Any], optional): Whether to add a best-fit line. Defaults to True. Pass a dict to customize line properties.
  • stats (bool | dict[str, Any], optional): Whether to display a text box with MAE and R^2. Defaults to True.
  • xlabel (str, optional): x-axis label. Auto-detected if None.
  • ylabel (str, optional): y-axis label. Auto-detected if None.
  • colorbar_kwargs (dict, optional): Passed to fig.layout.coloraxis.colorbar.
  • **kwargs: Additional keyword arguments passed to go.Scatter().

Returns go.Figure: Plotly Figure object

density_scatter_with_hist(x: ArrayLike | str, y: ArrayLike | str, *, df: pd.DataFrame | None=None, bins: int=100, density: Literal['kde', 'empirical'] | None=None, log_density: bool | None=None, n_bins: int | Literal[False] | None=None, **kwargs: Any) -> go.Figure

source

Scatter plot colored by density with marginal histograms along each dimension.

Args

  • x (array | str): x-values or dataframe column name.
  • y (array | str): y-values or dataframe column name.
  • df (pd.DataFrame, optional): DataFrame with x and y columns. Defaults to None.
  • bins (int, optional): Number of bins for marginal histograms. Defaults to 100.
  • density ("kde" | "empirical" | None): Method for density calculation.
  • log_density (bool | None): Whether to log-scale the density colors.
  • n_bins (int | None | False): Number of bins for empirical density calculation.
  • **kwargs: Additional arguments passed to the main density scatter plot.

Returns go.Figure: Plotly Figure with marginal histograms.

density_hexbin_with_hist(x: ArrayLike | str, y: ArrayLike | str, *, df: pd.DataFrame | None=None, bins: int=100, gridsize: int=75, **kwargs: Any) -> go.Figure

source

Hexagonal-grid scatter plot colored by density with marginal histograms along each dimension.

Args

  • x (array | str): x-values or dataframe column name.
  • y (array | str): y-values or dataframe column name.
  • df (pd.DataFrame, optional): DataFrame with x and y columns. Defaults to None.
  • bins (int, optional): Number of bins for marginal histograms. Defaults to 100.
  • gridsize (int, optional): Number of hexagons in the x and y directions. Defaults to 75.
  • **kwargs: Passed to density_hexbin().

Returns go.Figure: Plotly Figure with marginal histograms.

module pymatviz.structure.figures

structure_2d(struct: AnyStructure | Mapping[str, AnyStructure] | Sequence[AnyStructure] | pd.Series, *, rotation: str='10x,8y,3z', atomic_radii: float | dict[str, float] | None=None, atom_size: float=30, elem_colors: ElemColorScheme | dict[str, ColorType]=ElemColorScheme.jmol, scale: float=1, show_cell: bool | Mapping[Any, Any]=True, show_cell_faces: bool | dict[str, Any]=True, show_sites: bool | dict[str, Any]=True, show_image_sites: bool | dict[str, Any]=True, cell_boundary_tol: float | dict[str, float]=0.0, show_bonds: bool | NearNeighbors | dict[str, bool | NearNeighbors]=False, site_labels: Literal['symbol', 'species', 'legend', False] | dict[str, str] | Sequence[str]='legend', standardize_struct: bool | None=None, n_cols: int=3, subplot_title: Callable[[AnyStructure, Hashable], str | dict[str, Any]] | Literal[False] | None=None, show_site_vectors: str | Sequence[str]=('force', 'magmom'), show_image_vectors: bool=True, vector_kwargs: dict[str, dict[str, Any]] | None=None, hover_text: SiteCoords | Callable[[PeriodicSite], str]=SiteCoords.cartesian_fractional, hover_float_fmt: str | Callable[[float], str]='.4', bond_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Plot pymatgen structures in 2D with Plotly.

Args

  • struct (AnyStructure | Sequence[AnyStructure]): Pymatgen Structure(s) or ASE Atoms to plot.
  • rotation (str, optional): Rotation angles in degrees in the form '10x,20y,30z' from which to view the structure. Defaults to "10x,8y,3z".
  • atomic_radii (float | dict[str, float], optional): Either a scaling factor for default radii or map from element symbol to atomic radii. Defaults to None.
  • atom_size (float, optional): Scaling factor for atom sizes. Defaults to 40.
  • elem_colors (ElemColorScheme | dict[str, ColorType], optional): Element color scheme or custom color map. Defaults to ElemColorScheme.jmol.
  • scale (float, optional): Scaling of the plotted atoms and lines. Defaults to 1.
  • show_cell (bool | dict[str, Any], optional): Whether to render the cell. A dict with "node"/"edge" keys customizes node/edge appearance. A dict keyed by structure keys sets bool | style per structure (missing keys get the default cell). Defaults to True.
  • show_cell_faces (bool | dict[str, Any], optional): Whether to show transparent cell faces. If a dict, will customize surfaces style. Defaults to True.
  • show_sites (bool | dict[str, Any], optional): Whether to plot atomic sites. If a dict, will be used to customize site marker appearance. Defaults to True.
  • show_image_sites (bool | dict[str, Any], optional): Whether to show image sites on cell edges and surfaces. If a dict, will be used to customize how image sites are rendered. Defaults to True.
  • cell_boundary_tol (float | dict[str, float], optional): Buffer distance (in fractional coordinates) beyond the unit cell boundaries to include image atoms. Defaults to 0.0 for strict cell boundaries (only atoms with 0 <= coord <= 1). Higher values include atoms further outside the cell. If a dict, will be used to customize cell boundary tolerance per structure. Can also be set per-structure via Structure.properties["cell_boundary_tol"] or Atoms.info["cell_boundary_tol"] with highest precedence.
  • show_bonds (bool | NearNeighbors | dict[str, bool | NearNeighbors], optional): Whether to draw bonds between sites. If True, uses CrystalNN with a cutoff of 10 Å to determine nearest neighbors, including in neighboring cells. If a NearNeighbors object, uses that to determine nearest neighbors. If a dict, allows per-structure settings. Defaults to False (since still experimental).
  • site_labels ("symbol" | "species" | "legend" | False | dict | Sequence): How to annotate lattice sites. Defaults to "legend" (show an element color legend). Other options: "symbol", "species", False (no labels), a dict mapping site index to label, or a sequence of labels.
  • standardize_struct (bool, optional): Whether to standardize the structure. Defaults to None.
  • n_cols (int, optional): Number of columns for subplots. Defaults to 4.
  • subplot_title (Callable[[Structure, str | int], str | dict] | False, optional): Function to generate subplot titles. Defaults to lambda struct_i, idx: f"{idx}. {struct_i.formula} (spg={spg_num})". Set to False to hide all subplot titles.
  • show_site_vectors (str | Sequence[str], optional): Whether to show vector site quantities such as forces or magnetic moments as arrow heads originating from each site. Pass the key (or sequence of keys) to look for in site properties. Defaults to ("force", "magmom"). If not found as a site property, will look for it in the structure properties as well and assume the key points at a (N, 3) array with N the number of sites. If multiple keys are provided, it plots the first key found in site properties or structure properties in any of the passed structures (if a dict of structures was passed). But it will only plot one vector per site and it will use the same key for all sites and across all structures.
  • show_image_vectors (bool, optional): Whether to show vectors at image site positions. Only has effect when both show_image_sites and show_site_vectors are active. Defaults to True.
  • vector_kwargs (dict[str, dict[str, Any]], optional): For customizing vector arrows. Keys are property names (e.g., "force", "magmom"), values are dictionaries of arrow customization options. Use key "scale" to adjust vector length.
  • hover_text (SiteCoords | Callable, optional): Controls the hover tooltip template. Can be SiteCoords.cartesian, SiteCoords.fractional, SiteCoords.cartesian_fractional, or a callable that takes a site and returns a custom string. Defaults to SiteCoords.cartesian_fractional.
  • hover_float_fmt (str | Callable[[float], str], optional): Float formatting for hover coordinates. Can be an f-string format like ".4" (default) or a callable that takes a float and returns a string. Defaults to ".4".
  • bond_kwargs (dict[str, Any], optional): For customizing bond lines. Keys are line properties (e.g., "color", "width"), values are the corresponding values. Defaults to None.

Returns go.Figure: Plotly figure showing the 2D structure(s).

structure_3d(struct: AnyStructure | Mapping[str, AnyStructure] | Sequence[AnyStructure] | pd.Series, *, atomic_radii: float | dict[str, float] | None=None, atom_size: float=20, elem_colors: ElemColorScheme | dict[str, ColorType]=ElemColorScheme.jmol, scale: float=1, show_cell: bool | Mapping[Any, Any]=True, show_cell_faces: bool | dict[str, Any]=True, show_sites: bool | dict[str, Any]=True, show_image_sites: bool | dict[str, Any]=True, cell_boundary_tol: float | dict[str, float]=0.0, show_bonds: bool | NearNeighbors | dict[str, bool | NearNeighbors]=False, site_labels: Literal['symbol', 'species', 'legend', False] | dict[str, str] | Sequence[str]='legend', standardize_struct: bool | None=None, n_cols: int=3, subplot_title: Callable[[AnyStructure, Hashable], str | dict[str, Any]] | Literal[False] | None=None, show_site_vectors: str | Sequence[str]=('force', 'magmom'), show_image_vectors: bool=True, vector_kwargs: dict[str, dict[str, Any]] | None=None, hover_text: SiteCoords | Callable[[PeriodicSite], str]=SiteCoords.cartesian_fractional, hover_float_fmt: str | Callable[[float], str]='.4', bond_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Plot pymatgen structures in 3D with Plotly.

Takes the same arguments as structure_2d (minus rotation, since 3D scenes can be rotated interactively). atom_size defaults to 20.

Returns go.Figure: Plotly figure showing the 3D structure(s).

module pymatviz.structure.helpers

resolve_per_struct_params(raw_struct: AnyStructure, struct_key: Hashable, elem_colors: Any, cell_boundary_tol: float | dict[str, float], atomic_radii: float | dict[str, float] | None, atom_size: float | dict[str, float], scale: float | dict[str, float]) -> tuple[dict[str, ColorType], float, dict[str, float], Any, Any]

source

Resolve per-structure display params (struct properties > function args, dict args keyed by struct_key). Uses is None checks (not truthiness) so legitimate falsy values like 0.0 are respected. Returns a tuple of (elem_colors, cell_boundary_tol, atomic_radii, atom_size, scale).

resolve_nn_obj(show_bonds: bool | NearNeighbors | Mapping[Any, Any], struct_key: Hashable) -> NearNeighbors | None

source

Resolve show_bonds (True -> CrystalNN(), NearNeighbors -> itself, mapping -> lookup by struct_key) to the NearNeighbors algorithm for bond drawing, or None if bonds should not be drawn for this structure.

resolve_show_cell(show_cell: bool | Mapping[Any, Any], struct_key: Hashable) -> bool | dict[str, Any]

source

Resolve show_cell for one structure: a bool, a draw_cell style dict (only "edge"/"node" keys) applied to every structure, or a mapping of struct_key to bool | style dict. Structures missing from such a mapping get the default cell.

get_struct_prop(struct: AnyStructure, struct_key: Hashable, prop_name: str, func_param: Any) -> Any

source

Get a structure related value with standardized precedence handling.

Precedence order:

  1. structure.properties[prop_name] or atoms.info[prop_name]
  2. func_param (if dict, use struct_key; otherwise use directly)

Args

  • struct (AnyStructure): The pymatgen Structure or ASE Atoms object.
  • struct_key (Hashable): Key identifying this structure in a collection.
  • prop_name (str): Name of the property to look for in structure.properties or atoms.info.
  • func_param (Any): Function parameter value (can be dict for per-structure values).

Returns

  • Any: Resolved property value following precedence.

get_site_species(site: Site) -> Composition | Species | Element

source

Get species/composition from a site (handles ordered and disordered sites).

get_site_elements(site: Site) -> set[str]

source

Get element symbols from a site (handles ordered and disordered sites).

get_site_symbol(site: Site) -> str

source

Get single element symbol for a site (picks highest occupancy for disordered).

get_image_sites(site: PeriodicSite, lattice: Lattice, cell_boundary_tol: float=0.0, min_dist_dedup: float=0.1) -> np.ndarray

source

Get images for a given site in a lattice.

Images are sites that are integer translations of the given site that are within or near the cell boundaries.

Args

  • site (PeriodicSite): The site to get images for.
  • lattice (Lattice): The lattice to get images for.
  • cell_boundary_tol (float): Distance (in fractional coordinates) beyond the unit cell boundaries to include image atoms. Defaults to 0 for strict cell boundaries (only atoms with 0 <= coord <= 1). Higher values include atoms further outside the cell.
  • min_dist_dedup (float): The min distance in Angstroms to any other site to avoid finding image atoms that are duplicates of original basis sites. Defaults to 0.1.

Returns np.ndarray: Coordinates of all image sites.

get_elem_colors(elem_colors: ElemColorScheme | Mapping[str, ColorType]) -> dict[str, ColorType]

source

Get element colors based on the provided scheme or custom dictionary.

get_atomic_radii(atomic_radii: float | dict[str, float] | None) -> dict[str, float]

source

Get atomic radii based on the provided input.

get_elem_radius(atomic_radii: Mapping[str, float], elem_symbol: str) -> float

source

Look up an element's radius, raising an informative KeyError if a custom atomic_radii dict doesn't cover it. Dummy species (e.g. "X", no physical radius) missing from atomic_radii get missing_covalent_radius.

generate_site_label(site_labels: Literal['symbol', 'species', 'legend', False] | dict[str, str] | Sequence[str], site_idx: int, site: PeriodicSite) -> str | None

source

Generate a label for a given site based on the site_labels strategy.

Args

  • site_labels ("symbol" | "species" | "legend" | False] | dict[str, str]): The labeling strategy. If "legend", returns None. Can be "symbol", "species", "legend", False, a dict mapping symbols to custom labels, or a sequence of labels indexed by site position.
  • site_idx (int): The index of the site.
  • site: The site object.

Returns str | None: The generated label or None if no label should be shown.

Raises

  • ValueError: If site_labels is an unknown option or a sequence too short to label site_idx.

get_subplot_title(struct_i: AnyStructure, struct_key: Hashable, idx: int, subplot_title: Callable[[AnyStructure, Hashable], str | dict[str, Any]] | None) -> dict[str, Any]

source

Generate a subplot title based on the provided function or default logic.

get_site_hover_text(site: PeriodicSite, hover_text: SiteCoords | Callable[[PeriodicSite], str], majority_species: Species | Element | Composition, float_fmt: str | Callable[[float], str]='.4') -> str

source

Generate hover text for a site based on the hover template.

Args

  • site (PeriodicSite): The periodic site.
  • hover_text (SiteCoords | Callable[[PeriodicSite], str]): The hover text template or a custom callable.
  • majority_species (Species | Element | Composition): The majority species at the site.
  • float_fmt (str | Callable[[float], str]): Float formatting for coordinates. Can be an f-string format like ".4" (default) or a callable that takes a float and returns a string.

Returns

  • str: The formatted hover text string.

normalize_elem_color(raw_color_from_map: ColorType) -> str

source

Process a color from the element color map into a consistent RGB string format.

Args

  • raw_color_from_map (ColorType): Color value from the element color map (CSS color string or RGB tuple/list). RGB channels are treated as 0-1 floats unless any channel exceeds 1, in which case all are 0-255 (same rule as pymatviz.utils.plotting.rgb_components).

Returns

  • str: Color string. RGB tuples become "rgb(r,g,b)", strings pass through.

Raises

  • ValueError: If the color is neither a string nor a 3-channel numeric RGB.

draw_site(fig: go.Figure, site: PeriodicSite, coords: np.ndarray, site_idx: int, site_labels: Any, elem_colors: dict[str, ColorType], atomic_radii: dict[str, float], atom_size: float, scale: float, site_kwargs: dict[str, Any], *, is_image: bool=False, is_3d: bool=False, row: int | None=None, col: int | None=None, scene: str | None=None, hover_text: SiteCoords | Callable[[PeriodicSite], str]=SiteCoords.cartesian_fractional, float_fmt: str | Callable[[float], str]='.4', legendgroup: str | None=None, showlegend: bool=False, legend: str='legend', **kwargs: Any) -> None

source

Add a site (regular or image) to the plot.

Args

  • fig (go.Figure): The plotly figure to add the site to.
  • site (PeriodicSite): The periodic site to draw.
  • coords (np.ndarray): The coordinates of the site.
  • site_idx (int): The index of the site.
  • site_labels (str | dict | list): How to label the site.
  • elem_colors (dict[str, ColorType]): Element color mapping.
  • atomic_radii (dict[str, float]): Atomic radii mapping.
  • atom_size (float): Scaling factor for atom sizes.
  • scale (float): Overall scaling factor.
  • site_kwargs (dict[str, Any]): Additional keyword arguments for site styling.
  • is_image (bool): Whether this is an image site.
  • is_3d (bool): Whether this is a 3D plot.
  • row (int | None): Row for subplot.
  • col (int | None): Column for subplot.
  • scene (str | None): Scene name for 3D plots.
  • hover_text (SiteCoords | Callable[[PeriodicSite], str]): Hover text template.
  • float_fmt (str | Callable[[float], str]): Float formatting for hover coordinates.
  • legendgroup (str | None): For interactive legend. If None (default), will be set to the site's species symbol.
  • showlegend (bool): Whether to show this trace in the legend.
  • legend (str): The legend group for the site. If None (default), will be set to the site's species symbol.
  • **kwargs: Additional keyword arguments.

get_disordered_site_legend_name(sorted_species: Sequence[tuple[Species | Element, float]], *, is_image: bool=False) -> str

source

Create a legend name for a disordered site showing all elements with occupancies.

Args

  • sorted_species (list[tuple[Species, float]]): List of (Species, occupancy) tuples sorted by occupancy
  • is_image (bool): Whether this is an image site

Returns

  • str: Combined legend name like "Fe₀.₇₅Ni₀.₂₅"

draw_disordered_site(fig: go.Figure, site: PeriodicSite, coords: np.ndarray, site_idx: int, site_labels: Any, elem_colors: dict[str, ColorType], atomic_radii: dict[str, float], atom_size: float, scale: float, site_kwargs: dict[str, Any], *, is_image: bool=False, is_3d: bool=False, row: int | None=None, col: int | None=None, scene: str | None=None, hover_text: SiteCoords | Callable[[PeriodicSite], str]=SiteCoords.cartesian_fractional, float_fmt: str | Callable[[float], str]='.4', legendgroup: str | None=None, showlegend: bool=False, legend: str='legend', **kwargs: Any) -> None

source

Draw a disordered site as colored pie slices (2D) or spherical wedges (3D).

Occupancies set angular spans and, in 3D, wedge radii. Args are the same as for draw_site, except legendgroup defaults to one group per disordered site and extra kwargs are ignored.

get_spherical_wedge_mesh(center: np.ndarray, radius: float, start_angle: float, end_angle: float, n_theta: int=16, n_phi: int=24) -> tuple[list[float], list[float], list[float], list[int], list[int], list[int]]

source

Generate a spherical wedge mesh between two azimuthal angles for 3D pie charts.

Args

  • center (np.ndarray): Center coordinates (x, y, z) of the sphere
  • radius (float): Radius of the sphere
  • start_angle (float): Starting azimuthal angle in radians
  • end_angle (float): Ending azimuthal angle in radians
  • n_theta (int): Number of divisions in polar direction (from top to bottom)
  • n_phi (int): Number of divisions in azimuthal direction (around the wedge)

Returns tuple[list[float], list[float], list[float], list[int], list[int], list[int]]: A 6-tuple containing: - x_coords: x-coordinates for all mesh vertices - y_coords: y-coordinates for all mesh vertices - z_coords: z-coordinates for all mesh vertices - i_indices: first vertex indices for triangular faces - j_indices: second vertex indices for triangular faces - k_indices: third vertex indices for triangular faces

draw_vector(fig: go.Figure, start: np.ndarray, vector: np.ndarray, *, is_3d: bool=False, arrow_kwargs: dict[str, Any] | None=None, **kwargs: Any) -> None

source

Add an arrow representing a vector to a Plotly figure: a line shaft plus cone head in 3D, a line with an arrow marker in 2D.

Args

  • fig (go.Figure): The Plotly figure to add the arrow to.
  • start (np.ndarray): The starting point of the arrow (shape: (3,) for 3D, (2,) for 2D).
  • vector (np.ndarray): The vector to be represented by the arrow (shape: (3,) for 3D, (2,) for 2D).
  • is_3d (bool, optional): Whether to add a 3D arrow. Defaults to False.
  • arrow_kwargs (dict[str, Any] | None, optional): Additional keyword arguments for arrow customization. Supported keys: - color (str): Color of the arrow. - width (float): Width of the arrow shaft. - arrow_head_length (float): Length of the arrowhead (3D only). - scale (float): Scaling factor for the vector length.
  • **kwargs: Additional keyword arguments passed to the Plotly trace(s).

draw_cell(fig: go.Figure, structure: Structure | IStructure, cell_kwargs: dict[str, Any], *, is_3d: bool=True, row: int | None=None, col: int | None=None, scene: str | None=None, rotation_matrix: np.ndarray | None=None, show_faces: bool | dict[str, Any]=False) -> go.Figure

source

Draw the cell of a structure in a 2D or 3D Plotly figure.

Args

  • fig (go.Figure): The plotly figure to add the cell to.
  • structure (Structure): The pymatgen structure.
  • cell_kwargs (dict[str, Any]): Cell styling with optional keys "edge" (plotly line kwargs) and "node" (plotly marker kwargs). Other keys raise.
  • is_3d (bool): Whether this is a 3D plot. Defaults to True.
  • row (int | None): Row for subplot. Defaults to None.
  • col (int | None): Column for subplot. Defaults to None.
  • scene (str | None): Scene name for 3D plots. Defaults to None.
  • rotation_matrix (np.ndarray | None): Rotation matrix for 2D projections. Defaults to None.
  • show_faces (bool | dict[str, Any]): Whether to show transparent cell surfaces. If a dict, customizes surface appearance with keys "color" and (3D only) "showscale". Other keys raise. Defaults to False.

Returns go.Figure: The updated plotly figure.

get_first_matching_site_prop(structures: Sequence[Structure | IStructure | IMolecule], prop_keys: Sequence[str], *, warn_if_none: bool=True, filter_callback: Callable[[str, Any], bool] | None=None) -> str | None

source

Find the first property key that exists in any of the passed structures' properties or site properties. Will look in site.properties first, then structure.properties.

Args

  • structures (Sequence[Structure]): pymatgen Structures to check.
  • prop_keys (Sequence[str]): Property keys to look for.
  • warn_if_none (bool, optional): Whether to warn if no matching property is found.
  • filter_callback (Callable[[str, Any], bool] | None, optional): A function that takes the property key and value, and returns True if the property should be considered a match. If None, all properties are considered matches.

Returns str | None: The first matching property key found, or None if no match is found.

resolve_vector_prop(structures: Iterable[Structure | IStructure | IMolecule], show_site_vectors: str | Sequence[str]) -> str | None

source

The one vector property (first of show_site_vectors holding 3D vectors in any structure) drawn for all sites of all structures. Only warns if none is found and show_site_vectors isn't the ("force", "magmom") default.

draw_bonds(fig: go.Figure, structure: Structure, nn: NearNeighbors, *, is_3d: bool=True, bond_kwargs: dict[str, Any] | None=None, row: int | None=None, col: int | None=None, scene: str | None=None, rotation_matrix: np.ndarray | None=None, elem_colors: dict[str, ColorType] | None=None, plotted_sites_coords: set[Xyz] | None=None) -> None

source

Draw bonds between atoms in the structure.

Args

  • fig (go.Figure): Plotly figure to add bonds to
  • structure (Structure): This structure can be augmented to include primary sites and all relevant image sites to ensure comprehensive bond drawing.
  • nn (NearNeighbors): NearNeighbors object to determine bonds
  • is_3d: Whether the plot is 3D
  • bond_kwargs (dict[str, Any] | None): Customization options for bonds. If bond_kwargs["color"] is a tuple/list of colors, gradient coloring will be used. If color=True and elem_colors is provided, the gradient will use the colors of the connected atoms.
  • row (int | None): Row index for 2D subplots
  • col (int | None): Column index for 2D subplots
  • scene (str | None): Scene name for 3D plots
  • rotation_matrix (np.ndarray | None): Rotation matrix for 2D plots
  • elem_colors (dict[str, ColorType] | None): Element color map, used for gradient coloring if color=True
  • plotted_sites_coords (set[Xyz] | None): Optional set of (x, y, z) tuples for sites that are actually plotted. If provided, bonds will only be drawn if both end points are in this set. Coordinates are expected to be unrotated Cartesian coordinates rounded to 5 decimals.

Each bond is drawn once even though nn.get_nn_info reports it from both ends.

make_structure_grid(n_structs: int, n_cols: int, *, is_3d: bool, **kwargs: Any) -> tuple[go.Figure, int, int]

source

Figure with one (2D or scene) subplot per structure in a row-major grid.

Returns tuple[go.Figure, int, int]: Figure, number of rows and number of columns.

subplot_domain(idx: int, n_cols: int, n_rows: int, gap: float=0) -> tuple[list[float], list[float]]

source

Paper-coordinate x and y domains of the 1-based idx-th subplot in a row-major grid (rows top to bottom), shrunk by gap / 2 on every side.

style_scene_grid(fig: go.Figure, n_structs: int, n_cols: int, n_rows: int, **scene_kwargs: Any) -> None

source

Hide scene axes, keep data aspect ratios and tile scenes with a small gap.

set_subplot_title(fig: go.Figure, anno: dict[str, Any], idx: int, n_cols: int, n_rows: int) -> None

source

Pin the idx-th subplot title annotation just below its subplot's top edge.

configure_subplot_legends(fig: go.Figure, site_labels: Literal['symbol', 'species', 'legend', False] | dict[str, str] | Sequence[str], n_structs: int, n_cols: int, n_rows: int) -> None

source

Place each subplot's legend in its bottom right corner if site_labels is 'legend'.

add_vacuum_if_needed(struct: Any) -> Any

source

Add vacuum to ASE Atoms if they lack a proper cell.

module pymatviz.sunburst.chem_env

chem_env_sunburst(structures: PeriodicStructure | Sequence[PeriodicStructure], *, chem_env_settings: ChemEnvSettings='crystal_nn', normalize: bool=False, max_coordination_numbers: int | None=None, max_environments: int | None=None, mode: Literal['other', 'drop']='other', **widget_options: Any) -> SunburstWidget

source

Show coordination numbers and their chemical environments as a sunburst.

Use CrystalNN (default), "chemenv", or a dict of ChemEnv settings. With normalize=True, each structure with at least one classified environment contributes one total count before pruning (structures without environments contribute zero). Limit the most frequent coordination numbers and environments per coordination number with max_coordination_numbers and max_environments. Mode "other" combines omitted counts into one leaf per group; "drop" omits them. Additional options go to SunburstWidget.

module pymatviz.sunburst.chem_sys

chem_sys_sunburst(data: Sequence[str | Composition | Structure], *, group_by: FormulaGroupBy='chem_sys', max_systems: int | None=None, mode: Literal['other', 'drop']='other', **kwargs: Any) -> SunburstWidget

source

Show chemical systems within each arity as an interactive sunburst.

Input can contain formulas, chemical systems such as "Fe-O", compositions, and structures. Set group_by="formula" or "reduced_formula" to add formula leaves. A positive max_systems keeps the most frequent systems per arity (alphabetical ties) and all their formulas. mode="other" combines the rest in one leaf per arity; "drop" excludes their counts. Additional options, such as label_text and max_depth, go to SunburstWidget.

module pymatviz.sunburst.spacegroup

spacegroup_sunburst(data: Sequence[int | str | Structure] | pd.Series, *, show_counts: ShowCounts='value', max_slices: int | None=None, max_slices_mode: Literal['other', 'drop']='other', **kwargs: Any) -> go.Figure

source

Generate a sunburst plot with crystal systems as the inner ring for a list of international space group numbers.

Hint: To hide very small labels, set a uniformtext minsize and mode='hide'. fig.update_layout(uniformtext=dict(minsize=9, mode="hide"))

Args

  • data (list[int] | pd.Series): A sequence (list, tuple, pd.Series) of space group strings or numbers (from 1 - 230) or pymatgen structures.
  • show_counts ("value" | "percent" | "value+percent" | False): Whether to display values below each labels on the sunburst.
  • max_slices (int | None): Maximum number of space groups to show for each crystal system. If None (default), all space groups are shown. If positive integer, only the top N space groups by count are shown.
  • max_slices_mode ("other" | "drop"): How to handle spacegroups beyond max_slices: - "other": Combine remaining space groups into an "Other" slice (default) - "drop": Discard remaining space groups entirely
  • color_discrete_sequence (list[str]): A list of 7 colors, one for each crystal system. Defaults to plotly.express.colors.qualitative.G10.
  • **kwargs: Additional keyword arguments passed to plotly.express.sunburst.

Returns

  • Figure: The Plotly figure.

Raises

  • ValueError: If data is empty.

module pymatviz.templates

set_plotly_template(template: Literal['pymatviz_white', 'pymatviz_dark'] | str | go.layout.Template) -> None

source

Set the default plotly express and graph objects template.

Args

  • template ("pymatviz_white" | "pymatviz_dark" | go.layout.Template): Usually "pymatviz_white" or "pymatviz_dark" but any plotly.io.template name or the object itself is valid.

Raises

  • ValueError: If the template is not recognized.

module pymatviz.treemap.chem_env

chem_env_treemap(structures: PeriodicStructure | Sequence[PeriodicStructure], *, chem_env_settings: ChemEnvSettings='crystal_nn', normalize: bool=False, max_coordination_numbers: int | None=None, max_environments: int | None=None, mode: Literal['other', 'drop']='other', **widget_options: Any) -> TreemapWidget

source

Show coordination numbers and their chemical environments as a treemap.

Use CrystalNN (default), "chemenv", or a dict of ChemEnv settings. With normalize=True, each structure with at least one classified environment contributes one total count before pruning (structures without environments contribute zero). Limit the most frequent coordination numbers and environments per coordination number with max_coordination_numbers and max_environments. Mode "other" combines omitted counts into one leaf per group; "drop" omits them. Additional options go to TreemapWidget.

module pymatviz.treemap.chem_sys

chem_sys_treemap(data: Sequence[str | Composition | Structure], *, group_by: FormulaGroupBy='chem_sys', max_systems: int | None=None, mode: Literal['other', 'drop']='other', **kwargs: Any) -> TreemapWidget

source

Show chemical systems within each arity as an interactive treemap.

Input can contain formulas, chemical systems such as "Fe-O", compositions, and structures. Set group_by="formula" or "reduced_formula" to add formula leaves. A positive max_systems keeps the most frequent systems per arity (alphabetical ties) and all their formulas. mode="other" combines the rest in one leaf per arity; "drop" excludes their counts. Additional options, such as label_text and max_depth, go to TreemapWidget.

module pymatviz.treemap.py_pkg

ModuleStats

source

NamedTuple for holding module metrics, providing attribute access.

default_module_formatter(module: str, count: int, total: int) -> str

source

Default formatter showing module name, line count, and percentage on one line.

Example output: my_package (1,234 Lines, 15.6%)

count_lines(file_path: str, comment_prefixes: tuple[str, ...]=('#',)) -> int

source

Count non-empty, non-comment lines in a source file.

Args

  • file_path: Path to the source file.
  • comment_prefixes: Comment prefix strings to skip (e.g. ("#",) for Python, ("//",) for Rust/C/JS). Defaults to Python-style.

find_package_path(package_name: str) -> str

source

Find the filesystem path for an installed Python package.

collect_package_modules(package_names: Sequence[str | ModuleType], ignored_dirs: tuple[str, ...]=('.venv', '.git', 'node_modules')) -> pd.DataFrame

source

Collect information about all modules in the given packages.

Args

  • package_names (Sequence[str | ModuleType]): Names of packages to analyze or module objects.
  • ignored_dirs (tuple[str, ...]): Directories to ignore when scanning packages.

Returns pd.DataFrame: with package structure info

collect_source_modules_from_dir(source_dir: str, project_names: list[str], file_extensions: tuple[str, ...]=('.py',), ignored_dirs: tuple[str, ...]=('.git', 'target', 'node_modules', '.venv', '__pycache__', 'build', 'dist')) -> pd.DataFrame

source

Collect information about source files in a directory tree.

Language-agnostic alternative to :func:collect_package_modules. Walks the given source directory and builds a module hierarchy from the file system structure. Works for any language (Rust, TypeScript, Go, ...).

Args

  • source_dir: Root directory to scan for source files.
  • project_names: Display name(s) for the project. Files are attributed to the first name.
  • file_extensions: File extensions to include, e.g. (".rs",) for Rust or (".ts", ".tsx") for TypeScript.
  • ignored_dirs: Directory names to skip during traversal.

Returns pd.DataFrame with the same schema as :func:collect_package_modules.

py_pkg_treemap(packages: str | ModuleType | Sequence[str | ModuleType], *, source_dir: str | None=None, file_extensions: tuple[str, ...]=('.py',), base_url: str | None='auto', show_counts: ShowCounts='value+percent', cell_text_fn: ModuleFormatter | bool=default_module_formatter, group_by: GroupBy='module', max_module_depth: int | None=None, min_lines_for_split: int=0, max_children_for_split: int | None=None, cell_size_fn: CellSizeFn | None=None, color_by: str | dict[str, float] | None=None, color_range: tuple[float, float] | None=None, cell_border: dict[str, Any] | None=None, **kwargs: Any) -> go.Figure

source

Generate a treemap plot showing module structure of source code packages.

Works with any language when source_dir is provided. Without it, defaults to Python package introspection via importlib.

The first level shows the distribution by package, and the second level shows modules or files, with cell sizes typically indicating code size.

Args

  • packages (str | ModuleType | Sequence[str | ModuleType]): Single package name/module or list of package names/modules to analyze. When source_dir is provided, this is used only as a display label.
  • source_dir (str | None): Path to a source directory to scan instead of using Python importlib. Enables language-agnostic usage — e.g. point at a Rust src/ or TypeScript src/ folder. When provided, files are discovered by walking the directory tree rather than introspecting installed Python packages. Defaults to None (Python package mode).
  • file_extensions (tuple[str, ...]): File extensions to include when using source_dir. Defaults to (".py",). Use (".rs",) for Rust, (".ts", ".tsx") for TypeScript, etc. Ignored when source_dir is None.
  • base_url (str | None): Base URL for the source code repository (e.g., GitHub). If provided, the label of each module/file cell is turned into a clickable link pointing to the corresponding source file. Example: 'https://github.com/user/repo/blob/main' If set to "auto" (default), attempts to automatically find the GitHub URL from package metadata (requires package to be installed). Assumes 'main' branch. Only works reliably for single-package plots. If set to None, no links will be generated.
  • show_counts (ShowCounts): How to display counts in treemap cells: - "value": Show calculated cell size value - "percent": Show percentage of parent - "value+percent": Show both (default) - False: Don't show counts
  • cell_text_fn (ModuleFormatter | bool): How to display top-level names + counts: - Function that takes name, count, total count and returns string - True: Use default_module_formatter - False: Don't add counts to top-level names
  • group_by (GroupBy): How to group the package modules: - "file": Group by filename - "directory": Group by top-level directory - "module": Group by top-level module (default)
  • max_module_depth (int | None): Maximum depth of the module hierarchy to display when group_by="module". Files deeper than this level are aggregated into their ancestor at the cutoff depth. For example, max_module_depth=1 shows only top-level modules (io, analysis, core, ...), while max_module_depth=2 also shows sub-packages (io/vasp, analysis/chemenv, ...). If None (default), the full module hierarchy is shown.
  • min_lines_for_split (int): Minimum total lines of code for a child cell to be considered "significant" at a given depth. Children below this threshold are merged into an "other" bucket. If no children qualify as significant, the parent collapses into a single aggregated cell. Only applies when group_by="module". Defaults to 0 (no minimum).
  • max_children_for_split (int | None): Maximum number of significant child cells a parent may have at the deepest level. If a parent would produce more significant children than this, the split is suppressed and the parent stays aggregated. Intermediate levels are not affected, so large modules always show their sub-packages. Only applies when group_by="module". If None (default), no limit.
  • cell_size_fn (CellSizeFn | None): A callable that takes a ModuleStats object (a NamedTuple with fields like line_count, n_classes, n_functions, n_methods) and returns a number (int or float) to be used for the cell's size in the treemap. If this function returns 0, the corresponding module/file will be omitted from the treemap. If None (default), cell size is based on line_count.
  • color_by (str | dict[str, float] | None): Controls heatmap coloring mode: - str: Name of a numeric column in the module data to use for coloring (e.g. "line_count", "n_classes", "n_functions") - dict: Numeric values keyed by absolute file path or repo_path_segment. Absolute paths take precedence; missing files get zero. Pass labels={"color_value": "Coverage (%)"} for coverage percentages. - None: No heatmap coloring (default)
  • color_range (tuple[float, float] | None): Manual range for the color scale (min, max). Useful for consistent color mapping across plots or to ensure specific values (e.g., 0% coverage) map to specific colors. If None, uses the actual min/max values from the data.
  • cell_border (dict[str, Any] | None): Cell border styling. If None, defaults to white borders with width 0.5 for continuous coloring, no borders otherwise. Example: dict(color="black", width=2) for thick black borders.
  • **kwargs (Any): Additional keyword arguments passed to plotly.express.treemap

Returns go.Figure: The Plotly figure.

Tips and Customization:

  • rounded corners: fig.update_traces(marker=dict(cornerradius=5))
  • colors:
    • discrete: color_discrete_sequence=px.colors.qualitative.Set2
    • custom: color_discrete_map={'A': 'red', 'B': 'blue'}
  • max depth: fig.update_traces(maxdepth=2)
  • patterns/textures: fig.update_traces(marker=dict(pattern=dict(shape=["|"])))
  • hover info: fig.update_traces(hovertemplate='%{label}
    Lines: %{value}')
  • custom text display: fig.update_traces(textinfo="label+value+percent")

Example >>> import pymatviz as pmv >>> # Analyze a single package >>> fig1 = pmv.py_pkg_treemap("pymatviz") >>> # Compare multiple packages, coloring cells by function count >>> fig2 = pmv.py_pkg_treemap(["pymatviz", "pymatgen"], color_by="n_functions") >>> # Rust crate treemap (language-agnostic mode) >>> fig3 = pmv.py_pkg_treemap( ... "my_rust_crate", source_dir="src", file_extensions=(".rs",) ... )

module pymatviz.uncertainty

qq_gaussian(y_true: ArrayLike | str, y_pred: ArrayLike | str, y_std: ArrayLike | Mapping[str, ArrayLike] | str | Sequence[str], *, df: pd.DataFrame | None=None, fig: go.Figure | None=None, identity_line: bool | dict[str, Any]=True) -> go.Figure

source

Q-Q Gaussian plot for uncertainty calibration assessment.

Args

  • y_true: Ground truth targets
  • y_pred: Model predictions
  • y_std: Positive standard deviations (single array or dict for multiple)
  • df: DataFrame containing data columns
  • fig: Existing plotly figure to add to
  • identity_line: Show perfect calibration line

Returns go.Figure: plotly Figure with Q-Q plot

error_decay_with_uncert(y_true: ArrayLike | str, y_pred: ArrayLike | str, y_std: ArrayLike | Mapping[str, ArrayLike] | str | Sequence[str], *, df: pd.DataFrame | None=None, n_rand: int=100, percentiles: bool=True, fig: go.Figure | None=None) -> go.Figure

source

Error decay plot as uncertain samples are excluded.

Args

  • y_true: Ground truth targets
  • y_pred: Model predictions
  • y_std: Uncertainties (single array or dict for multiple)
  • df: DataFrame containing data columns
  • n_rand: Random shuffles for baseline
  • percentiles: Show excluded samples as a percentage rather than a count
  • fig: Existing plotly figure to add to

Returns Plotly figure with error decay plot

module pymatviz.utils.data

spg_to_crystal_sys(spg: float | str) -> CrystalSystem

source

Get the crystal system for an international space group number.

spg_num_to_from_symbol(spg: int | str) -> str | int

source

Get the Hermann-Mauguin short or full symbol for an international space group number or vice versa.

Args

  • spg (int | str): A space group number (int) or a Hermann-Mauguin symbol (str).

Returns int | str: str if input was a number, int if input was a str.

html_tag(text: str, tag: str='span', style: str='', title: str='') -> str

source

Wrap text in a span with custom style.

Style defaults to decreased font size and weight e.g. to display units in plotly labels and annotations.

Args

  • text (str): Text to wrap in span.
  • tag (str, optional): HTML tag name. Defaults to "span".
  • style (str, optional): CSS style string. Defaults to "". Special keys: "small": font-size: 0.8em; font-weight: lighter; "bold": font-weight: bold; "italic": font-style: italic; "underline": text-decoration: underline;
  • title (str | None, optional): Title attribute which displays additional information in a tooltip. Defaults to "".

Returns

  • str: HTML string with tag-wrapped text.

si_fmt(val: float, *, fmt: str='.1f', sep: str='', binary: bool=False, decimal_threshold: float=0.01) -> str

source

Convert large numbers into human readable format using SI suffixes.

Supports binary (1024) and metric (1000) mode.

https://nist.gov/pml/weights-and-measures/metric-si-prefixes

Args

  • val (int | float): Some numerical value to format.
  • binary (bool, optional): If True, scaling factor is 2^10 = 1024 else 1000. Defaults to False.
  • fmt (str): f-string format specifier. Configure precision and left/right padding in returned string. Defaults to ".1f". Can be used to ensure leading or trailing whitespace for shorter numbers. See https://docs.python.org/3/library/string.html#format-specification-mini-language.
  • sep (str): Separator between number and postfix. Defaults to "".
  • decimal_threshold (float): abs(value) below 1 but above this threshold will be left as decimals. Only below this threshold is a greek suffix added (milli, micro, etc.). Defaults to 0.01. i.e. 0.01 -> "0.01" while 0.0099 -> "9.9m". Setting decimal_threshold=0.1 would format 0.01 as "10m" and leave 0.1 as is.

Returns

  • str: Formatted number.

module pymatviz.utils.plotting

annotate(text: str | Sequence[str], fig: go.Figure, **kwargs: Any) -> go.Figure

source

Annotate a Plotly figure or its facets, skipping empty facet labels.

Args

  • text (str): The text to use for annotation. If fig is plotly faceted, text can be a list of strings, one per trace (empty strings are skipped). Several annotations in the same subplot are stacked downwards.
  • fig (go.Figure): The plotly Figure to annotate.
  • **kwargs: Additional arguments to pass to plotly's fig.add_annotation().

Returns go.Figure: The annotated figure.

Raises

  • TypeError: If fig is not a Plotly figure.

apply_show_counts(fig: go.Figure, show_counts: ShowCounts, value_fmt: str='') -> None

source

Set a treemap/sunburst trace's text to its label plus the counts selected by show_counts ("value", "percent", "value+percent" or False), formatting values with the d3 value_fmt (e.g. ".2f").

get_font_color(fig: go.Figure) -> str

source

Get the font color from a Plotly figure, its template, or the global template.

Defaults to black when no font color is set. Raises TypeError for non-figures.

rgb_components(color: ColorType) -> tuple[float, float, float]

source

Normalize a color to its red, green and blue channels in [0, 1].

Args

  • color (ColorType): RGB(A) tuple or list with channels in [0, 1] or [0, 255] (any channel > 1 means bytes), CSS color name, 3/6-digit hex string, or rgb()/rgba() string with byte channels. Alpha is dropped.

Returns tuple[float, float, float]: Red, green and blue channels in [0, 1].

Raises

  • ValueError: If the color format is unsupported or channels are out of range.

luminance(color: ColorType) -> float

source

Compute the relative luminance of a color using the WCAG 2.0 formula.

Args

  • color (ColorType): RGB color tuple with values in [0, 1] or [0, 255], or a color string (CSS name, hex, or rgb/rgba with channels in [0, 255]). Alpha is ignored.

Returns

  • float: Relative luminance of the color in range [0, 1].

contrast_ratio(color1: ColorType, color2: ColorType) -> float

source

Calculate the contrast ratio between two colors according to WCAG 2.0.

Args

  • color1 (ColorType): First color (RGB tuple with values in [0, 1] or [0, 255], or a color string that can be converted to RGB).
  • color2 (ColorType): Second color (RGB tuple with values in [0, 1] or [0, 255], or a color string that can be converted to RGB).

Returns

  • float: Contrast ratio between the two colors, ranging from 1:1 to 21:1.

pick_max_contrast_color(bg_color: ColorType, colors: tuple[ColorType, ColorType]=('white', 'black'), min_contrast_ratio: float=2.0) -> ColorType

source

Choose text color for a given background color based on WCAG 2.0 contrast ratio.

This function calculates the contrast ratio between the background color and each of the provided text colors, then returns the color with the highest contrast ratio. If the contrast ratio with white is above the minimum contrast ratio, white will be chosen even if black has a slightly higher contrast ratio. This ensures that darker colors always get white text, which is often more readable in 3D visualizations.

Args

  • bg_color (ColorType): Background color.
  • colors (tuple[ColorType, ColorType], optional): Text colors to choose from. Defaults to ("white", "black").
  • min_contrast_ratio (float, optional): Minimum contrast ratio to prefer white over black text. Defaults to 2.0 (lower than WCAG AA standard to ensure dark colors get white text).

Returns

  • ColorType: item in colors that provides the best contrast with bg_color.

get_fig_xy_range(fig: go.Figure, traces: int | slice | Sequence[int] | Callable[[go.Scatter], bool]=0, pad_frac: float=0.05) -> tuple[tuple[float, float], tuple[float, float]]

source

Get the x and y range of a plotly figure from its trace data.

Computed without rendering (no Kaleido). Approximates Plotly's autorange by padding the finite data bounds of the selected traces by pad_frac of their span on each side (in log10 space for log axes, ignoring non-positive values there). Axis bounds fixed via layout.xaxis.range/yaxis.range take precedence. Axis type and fixed range are read from the axes of the first selected trace, so traces spread over subplots (e.g. facets) share one combined range.

Args

  • fig (go.Figure): plotly figure.
  • traces (int | slice | Sequence[int] | Callable, optional): Specifies which trace(s) to use for determining the x/y range. Can be: - int: A single trace index (default: 0) - slice: A slice object to select a range of traces - list[int]: A list of specific trace indices - Callable: A function that takes a trace and returns True/False Selected traces without both non-empty x and y data are ignored.
  • pad_frac (float, optional): Fraction of the data span to pad on each side of auto-ranged axes. A zero-width span is padded by 1 (1 decade on log axes). Defaults to 0.05.

Returns

  • tuple: The axis ranges as ((x_min, x_max), (y_min, y_max)).

Raises

  • TypeError: If fig is not a plotly Figure.
  • ValueError: If no selected trace has x and y data, the selected traces span axes of different types, or an axis has no finite (positive for log) data.

annotated_heatmap(z: Any, x: Any=None, y: Any=None, annotation_text: Any=None, colorscale: Any='Plasma', font_colors: Any=None, *, showscale: bool=False, reversescale: bool=False, **kwargs: Any) -> go.Figure

source

Heatmap with a text annotation centered on every cell.

Args

  • z: 2D array of values driving the cell colors.
  • x: Column labels. Defaults to positional indices.
  • y: Row labels. Defaults to positional indices.
  • annotation_text: 2D array of per-cell text. Defaults to z.
  • colorscale: Any plotly colorscale, named or as a list of stops.
  • font_colors: Annotation colors for the low and high ends of the scale. Chosen from the colorscale for contrast when omitted.
  • showscale: Whether to draw the colorbar.
  • reversescale: Whether to reverse the colorscale.
  • **kwargs: Forwarded to the heatmap trace. zmin/zmax/zmid also move the threshold at which annotations switch between the two font colors.

Returns go.Figure: The annotated heatmap.

module pymatviz.utils.testing

formula_spg_str(struct: Structure) -> str

source

Get a string with formula and space group number for a structure.

Args

  • struct: A pymatgen Structure object.

Returns String in format "Formula (spg_number)", e.g. "NaCl (225)".

load_phonopy_nacl() -> Phonopy

source

Load phonopy NaCl object from test files.

Returns a Phonopy class instance of NaCl 2x2x2 without symmetrizing fc2. This function can be used in both tests and examples to get a consistent phonopy object for demonstrations.

Returns

  • Phonopy: Loaded phonopy object with force constants.

Raises

  • ImportError: If phonopy is not installed.

Example >>> phonopy_nacl = load_phonopy_nacl() >>> phonopy_nacl.run_mesh([10, 10, 10]) >>> phonopy_nacl.run_total_dos() >>> dos = phonopy_nacl.total_dos

module pymatviz.widgets.band_structure

BandStructureWidget

source

MatterViz widget for visualizing electronic and phonon band structures.

Accepts pymatgen BandStructure, BandStructureSymmLine, or PhononBandStructureSymmLine objects, or a pre-computed dict. Pass a {label: band_structure} dict to overlay several band structures.

Examples From a pymatgen BandStructureSymmLine: >>> from pymatviz import BandStructureWidget >>> widget = BandStructureWidget(band_structs=bs) >>> widget

With custom options:
>>> widget = BandStructureWidget(
...     band_structs={"PBE": bs_pbe, "HSE": bs_hse},
...     show_legend=True,
...     fermi_level=0.0,
...     style="height: 500px;",
... )

module pymatviz.widgets.bands_and_dos

BandsAndDosWidget

source

MatterViz widget for combined band structure + DOS visualization.

Renders bands on the left and DOS on the right with linked energy/frequency axes. Accepts pymatgen band structure and DOS objects, or pre-computed dicts. Pass {label: obj} dicts to overlay several band structures / DOS curves.

Examples From pymatgen objects: >>> from pymatviz import BandsAndDosWidget >>> widget = BandsAndDosWidget(band_structs=bs, doses=dos) >>> widget

With custom options:
>>> widget = BandsAndDosWidget(
...     band_structs=bs,
...     doses=dos,
...     style="height: 600px;",
... )

module pymatviz.widgets.bar_plot

BarPlotWidget

source

MatterViz widget wrapper for grouped/stacked/overlay bar plots.

module pymatviz.widgets.brillouin_zone

BrillouinZoneWidget

source

MatterViz widget for visualizing Brillouin zones.

Accepts a pymatgen Structure (BZ is computed by the matterviz frontend) or pre-computed BZ data with vertices, faces, and edges.

Examples From a pymatgen Structure: >>> from pymatviz import BrillouinZoneWidget >>> widget = BrillouinZoneWidget(structure=struct) >>> widget

With pre-computed BZ data:
>>> widget = BrillouinZoneWidget(bz_data=bz_dict)

With custom options:
>>> widget = BrillouinZoneWidget(
...     structure=struct,
...     show_ibz=True,
...     show_vectors=True,
...     style="height: 600px;",
... )

module pymatviz.widgets.chem_pot_diagram

ChemPotDiagramWidget

source

MatterViz widget for chemical potential diagrams.

Visualizes thermodynamic stability regions in chemical potential space from phase diagram entry data.

Examples >>> from pymatviz import ChemPotDiagramWidget >>> widget = ChemPotDiagramWidget( ... entries=[ ... {"name": "Li2O", "energy": -14.3, "composition": {"Li": 2, "O": 1}}, ... ], ... )

module pymatviz.widgets.composition

CompositionWidget

source

MatterViz widget for visualizing compositions in Python notebooks.

Examples Basic usage: >>> from pymatviz import CompositionWidget >>> from pymatgen.core import Composition >>> comp = Composition("Fe2O3") >>> widget = CompositionWidget(composition=comp) >>> widget

With custom visualization options:
>>> widget = CompositionWidget(
...     composition=comp,
...     mode="bar",
...     show_percentages=True,
...     color_scheme="Jmol",
...     style="width: 400px; margin: 20px auto;",
... )

module pymatviz.widgets.convex_hull

ConvexHullWidget

source

MatterViz widget for visualizing convex hull phase stability diagrams.

Supports binary, ternary, and quaternary convex hulls. Accepts either a pymatgen PhaseDiagram object or a list of entry dicts with composition and energy data.

Examples From a pymatgen PhaseDiagram: >>> from pymatviz import ConvexHullWidget >>> from pymatgen.analysis.phase_diagram import PhaseDiagram >>> pd = PhaseDiagram(entries) >>> widget = ConvexHullWidget(entries=pd) >>> widget

From a list of entry dicts:
>>> entries = [
...     {"composition": {"Li": 1}, "energy_per_atom": -1.5},
...     {"composition": {"Li": 1, "O": 2}, "energy_per_atom": -3.2},
... ]
>>> widget = ConvexHullWidget(entries=entries)

With custom visualization options:
>>> widget = ConvexHullWidget(
...     entries=pd,
...     show_unstable_labels=True,
...     temperature=300,
...     style="height: 600px;",
... )

module pymatviz.widgets.dos

DosWidget

source

MatterViz widget for visualizing electronic and phonon density of states.

Accepts pymatgen Dos, CompleteDos, or PhononDos objects, or a pre-computed dict. Pass a {label: dos} dict to overlay several DOS curves.

Examples From a pymatgen CompleteDos: >>> from pymatviz import DosWidget >>> widget = DosWidget(doses=complete_dos) >>> widget

With custom options:
>>> widget = DosWidget(
...     doses={"PBE": dos_pbe, "HSE": dos_hse},
...     sigma=0.05,
...     spin_mode="combined",
...     style="height: 500px;",
... )

module pymatviz.widgets.fermi_surface

FermiSurfaceWidget

source

MatterViz widget for visualizing Fermi surfaces.

Accepts pre-computed Fermi surface data (isosurfaces + reciprocal lattice) or raw band grid data (energies on a k-grid for marching cubes extraction). fermi_data: {isosurfaces: [{vertices, faces, normals?, band_index, spin}], k_lattice, fermi_energy} or an IFermi FermiSurface.as_dict(); band_data: {energies: [spin][band][kx][ky][kz], k_grid, k_lattice, fermi_energy}.

Examples From pre-computed Fermi surface data: >>> from pymatviz import FermiSurfaceWidget >>> widget = FermiSurfaceWidget(fermi_data=fermi_dict) >>> widget

From raw band grid data:
>>> widget = FermiSurfaceWidget(band_data=band_grid_dict)

With custom options:
>>> widget = FermiSurfaceWidget(
...     fermi_data=fermi_dict,
...     surface_opacity=0.8,
...     show_bz=True,
...     color_property="property",
...     color_bar={"title": "Fermi velocity"},  # None hides it
...     style="height: 600px;",
... )

module pymatviz.widgets.heatmap_matrix

HeatmapMatrixWidget

source

MatterViz widget for 2D heatmap/matrix visualizations.

Supports element-vs-element matrices, confusion matrices, and general labeled grids with color scaling.

Examples >>> from pymatviz import HeatmapMatrixWidget >>> widget = HeatmapMatrixWidget( ... x_items=["Fe", "O", "Li"], ... y_items=["Fe", "O", "Li"], ... values=[[1, 0.5, 0.2], [0.5, 1, 0.3], [0.2, 0.3, 1]], ... )

module pymatviz.widgets.histogram

HistogramWidget

source

MatterViz widget wrapper for histogram visualizations. Each series holds the raw samples to bin in values; binning happens in the frontend.

Assign a new series to update the data. Samples are normalized to numeric lists; invalid updates raise traitlets.TraitError and preserve prior data.

module pymatviz.widgets.link

source

Keep a shared selection index in sync across linked MatterViz widgets.

Each supported widget contributes a source (interaction it reports), a sink (how it reflects the shared index), or both:

  • TrajectoryWidget: source + sink via current_step_idx.
  • ScatterPlotWidget: source via active_point (clicked point index), sink via selected_point (highlight).
  • StructureWidget: sink only -- its structure is set to structures[index] (requires structures).

Re-entrancy is guarded so a sink update never echoes back into a new broadcast, and traitlets' own no-op-on-unchanged behavior prevents loops.

Remove all observers, stopping further synchronization.

source

Two-way link a shared selection index across MatterViz widgets.

Convenience wrapper around :class:WidgetLink. Clicking a scatter point or stepping a trajectory updates every other linked widget; a linked StructureWidget shows structures[index].

Args

  • *widgets: Widgets to link (need at least two). Supported: TrajectoryWidget, ScatterPlotWidget, StructureWidget.
  • structures: Ordered structures indexed by the selection index. Required if a StructureWidget is linked.
  • series_idx: Series index used when highlighting scatter points.

Returns A :class:WidgetLink whose unlink() stops synchronization.

module pymatviz.widgets.matterviz

configure_assets(*, version: str | None=None, esm_src: str | None=None, css_src: str | None=None) -> None

source

Configure matterviz widget assets globally for all subsequent widgets.

Call with no arguments to reset to default (MATTERVIZ_ANYWIDGET_VERSION).

Args

  • version: matterviz-anywidget npm version to fetch (e.g. "0.4.0"), or "main" for the bundle built from matterviz main. Mutually exclusive with esm_src/css_src.
  • esm_src: URL or local file path for the ESM JavaScript bundle.
  • css_src: URL or local file path for the CSS stylesheet. Derived from esm_src by replacing .js → .css if omitted.

fetch_widget_asset(filename: str, version_override: str | None=None) -> str

source

Fetch a widget asset (matterviz.js/matterviz.css) as source text.

The bundle lives in the matterviz-anywidget npm package (built from matterviz/extensions/anywidget); this repo no longer builds it. Resolution order

  1. MATTERVIZ_ANYWIDGET_DIR env var -- a local build/ dir, for developing against an unpublished bundle.
  2. on-disk cache (~/.cache/pymatviz/matterviz-anywidget/<version>/).
  3. download from _cdn_url(version) (jsDelivr for npm versions), cached.

version="main" skips the disk cache (steps 2 and 3's write): main's bundle changes with every matterviz deploy, so it is re-downloaded once per process (MatterVizWidget caches assets in memory).

Args

  • filename: "matterviz.js" or "matterviz.css".
  • version_override: matterviz-anywidget npm version (or "main") to fetch instead of the default MATTERVIZ_ANYWIDGET_VERSION.

clear_widget_cache(version_override: str | None=None) -> None

source

Clear the downloaded widget-asset cache.

Args

  • version_override: Only clear this matterviz-anywidget version's cache.

MatterVizWidget

source

Base widget class that lazily loads and caches MatterViz widget assets.

Note The marimo VS Code extension does not support virtual files, so widgets with large JS bundles (>5 MB) cannot render there. Use marimo edit in a browser instead.

show() -> None

Display this widget in notebook environments.

Safe to call as the last expression in a cell — returns None to prevent Jupyter from auto-displaying a second copy.

When the PYMATVIZ_STATIC env var is set, renders a static PNG via headless Chromium instead of the interactive widget protocol. Useful for CI notebook execution where outputs must be viewable without a live widget frontend (e.g. GitHub .ipynb rendering).

to_dict() -> dict[str, Any]

Return all public synced traitlet values as a plain dict.

to_img(filename: str | None=None, fmt: Literal['png', 'jpeg', 'svg', 'pdf'] | None=None, dpi: int=150, timeout: float=30.0, width: int | None=None, height: int | None=None, quality: int=90) -> bytes

Capture the widget as an image via headless Chromium rendering.

Launches a headless browser (reused across calls), loads the ESM bundle with the widget's data, waits for the component to render, and captures the output. Works in plain Python scripts, CI, and agent workflows -- no notebook frontend required.

Note: SVG export is only available for SVG-based (2D) widgets. Canvas layers inside the SVG chart (e.g. scatter markers with marker_renderer="canvas", the default above 1000 points) are embedded as PNG <image> elements; set marker_renderer="svg" for fully vector markers. Canvas-based widgets (Structure, Trajectory, etc.) always export as PNG/JPEG. PDF export uses Chromium's native PDF generator, producing vector output with selectable text (2D canvas layers embedded as images); only WebGL widgets get a rasterized PDF.

Requires playwright (install with uv pip install playwright && playwright install chromium).

Args

  • filename: Optional file path to write the image to. Format is inferred from the extension if fmt is not provided. Both .jpg and .jpeg extensions map to JPEG.
  • fmt: Image format -- "png", "jpeg", "svg", or "pdf". Defaults to "png" if not specified and cannot be inferred from filename.
  • dpi: Resolution for raster output. Maps to the headless browser's device scale factor (72 = 1x, 144 = 2x, etc.). Defaults to 150 (~2x). Applies to PNG/JPEG and to canvas pixels in SVG/PDF exports; pure-vector content is unaffected.
  • timeout: Seconds to wait for headless rendering before raising TimeoutError. Defaults to 30.
  • width: Override container width in pixels for this export. Takes precedence over the widget's style. If omitted, uses the widget's style or defaults to 800px.
  • height: Override container height in pixels for this export. Takes precedence over the widget's style. If omitted, uses the widget's style or defaults to 600px.
  • quality: JPEG compression quality (1-100). Defaults to 90. Ignored for PNG, SVG, and PDF.

Returns Raw image/document bytes (PNG, JPEG, SVG, or PDF).

Raises

  • ValueError: If fmt is not a supported format.
  • TimeoutError: If the widget does not finish rendering in time.
  • RuntimeError: If the widget fails to render or SVG export is requested for a canvas-based widget.
  • ImportError: If playwright is not installed.

describe() -> dict[str, Any]

Return structured, machine-parseable facts about this widget's data.

Pure Python (no browser): derives counts, ranges, formula, chemical system, etc. from the synced traitlets. Always includes widget_type. Useful for agents to reason about output and as image alt-text.

Examples >>> PeriodicTableWidget(heatmap_values={"Fe": 42}).describe()["n_elements"] 1

to_html(filename: str | None=None, *, inline: bool=False, esm_url: str | None=None) -> str

Export this widget as a standalone, interactive HTML page.

The page renders the live widget (pan/zoom/rotate/hover work) with no notebook required. By default it references the MatterViz bundle from a CDN, keeping the file small; pass inline=True for a self-contained file that opens offline.

Args

  • filename: Optional path to write the HTML to (parent dirs created).
  • inline: If True, embed the ~4.5 MB ESM bundle in the file (opens via file:// offline). If False (default), reference an external URL (small file, requires internet + a CORS-enabled JS host; will not load via file://).
  • esm_url: Explicit URL to load the bundle from (a host serving it with CORS and a JavaScript MIME type). Mutually exclusive with inline. When omitted and inline is False, references the bundle matching the widget's active assets (the MATTERVIZ_ANYWIDGET_VERSION URL by default, or the version/URL from configure_assets / version_override); local custom assets are inlined instead.

Returns The complete HTML document as a string.

Raises

  • ValueError: If both inline=True and esm_url are given.

Note Controls that round-trip through a Python kernel do not function in the exported page (there is no kernel); client-side interactions do.

render_report(*, timeout: float=30.0, dpi: int=72) -> RenderReport

Headlessly render this widget and report on its visual health.

Combines cheap input checks (empty/degenerate data) with a single headless render that measures whether the output is blank, clipped, and whether it is canvas/SVG/HTML. Intended for agents to self-verify a render without "looking" at it. Never raises -- failures populate RenderReport.error with ok=False.

Args

  • timeout: Seconds to wait for the headless render.
  • dpi: Capture resolution (affects the blank-fraction screenshot).

Returns A RenderReport (see its fields). Requires playwright; blank_fraction additionally requires Pillow (else None).

module pymatviz.widgets.mime

create_widget(obj: Any) -> Any

source

Create the appropriate MatterViz widget for a pymatgen/ASE/phonopy object.

Uses MRO-based type matching, so subclasses of registered types are handled automatically. Falls back to trajectory detection for list/tuple of structures.

Args

  • obj: A pymatgen Structure, Composition, BandStructure, Dos, PhaseDiagram, DiffractionPattern, or similar object.

Returns The appropriate widget instance.

Raises

  • ValueError: If no widget is registered for the given object type.

register_matterviz_widgets() -> None

source

Register pymatgen/ASE/phonopy classes for auto-display in notebooks.

Populates the _AUTO_DISPLAY registry and monkey-patches display on registered classes for marimo auto-rendering.

module pymatviz.widgets.periodic_table

PeriodicTableWidget

source

MatterViz widget for interactive periodic table visualizations.

Supports element heatmaps, custom color scales, labels, and click interaction.

Examples Heatmap by element counts: >>> from pymatviz import PeriodicTableWidget >>> widget = PeriodicTableWidget( ... heatmap_values={"Fe": 42, "O": 100, "Li": 15}, ... color_scale="interpolateViridis", ... )

Log-spaced colors clamped to a fixed lower bound, color bar hidden:
>>> widget = PeriodicTableWidget(
...     heatmap_values={"Fe": 42, "O": 100, "Li": 15},
...     color_scale={"type": "log", "value_range": [10, None]},
...     color_bar=None,
... )

module pymatviz.widgets.phase_diagram

PhaseDiagramWidget

source

MatterViz widget for visualizing isobaric binary phase diagrams.

Renders temperature-composition phase diagrams with regions, boundaries, and special points (eutectic, peritectic, etc.).

Note: This is NOT for pymatgen's PhaseDiagram class (use ConvexHullWidget for that). This widget renders binary phase diagrams with temperature-dependent phase regions.

Examples From a phase diagram data dict: >>> from pymatviz import PhaseDiagramWidget >>> data = { ... "components": ["Fe", "C"], ... "temperature_range": [300, 2000], ... "regions": [...], ... "boundaries": [...], ... } >>> widget = PhaseDiagramWidget(data=data) >>> widget

module pymatviz.widgets.rdf_plot

RdfPlotWidget

source

MatterViz widget for radial distribution function (RDF) plots.

Accepts pre-computed RDF patterns or structure data for on-the-fly computation. Provide either structures or patterns, not both.

Examples From a pymatgen Structure dict: >>> from pymatviz import RdfPlotWidget >>> widget = RdfPlotWidget( ... structures={"lattice": {...}, "sites": [...]}, cutoff=10 ... )

module pymatviz.widgets.scatter_plot

ScatterPlotWidget

source

MatterViz widget wrapper for 2D scatter/line plots.

The payload follows matterviz ScatterPlot props with a Python-friendly API.

module pymatviz.widgets.scatter_plot_3d

ScatterPlot3DWidget

source

MatterViz widget for 3D scatter/surface plots with camera controls.

Examples >>> from pymatviz import ScatterPlot3DWidget >>> widget = ScatterPlot3DWidget( ... series=[{"x": [1, 2], "y": [3, 4], "z": [5, 6], "label": "pts"}], ... )

module pymatviz.widgets.spacegroup_bar

SpacegroupBarPlotWidget

source

MatterViz widget for space group frequency bar plots.

Accepts space group numbers/symbols or {spacegroup: count} mappings and renders a bar chart showing their frequency distribution.

Examples >>> from pymatviz import SpacegroupBarPlotWidget >>> widget = SpacegroupBarPlotWidget(data=[225, 225, 166, 62, 62, 62])

module pymatviz.widgets.structure

volume_to_envelopes(volume: Any) -> list[dict[str, Any]]

source

Convert a volumetric dict (flat values + dims, nested grid, or a ready matterviz-binary-v1 volume envelope) or a pymatgen VolumetricData (one entry per data key, Chgcar values divided by the cell volume to e/ų like matterviz's CHGCAR parser) to binary volume envelopes (float32 grid, z fastest). id is what isosurface layers reference via volume_id: dicts use their id, else their label (like matterviz's file parsers), pymatgen volumes use their data key (e.g. "total", "diff").

Raises

  • TypeError: If volume is neither a dict nor a pymatgen VolumetricData. Lattice/origin/periodic errors are reported by the renderer.
  • ValueError: If a dict lacks an id/label, or a flat values doesn't match its dims or has non-finite values.

check_layer_volume_ids(isosurface_settings: Mapping[str, Any] | None, volumes: list[dict[str, Any]]) -> None

source

Raise if an isosurface layer lacks a volume_id or, for volumes passed from Python, references a volume_id/color_volume_id matching no volume (matterviz silently drops such layers). Volumes loaded from data_url are parsed in the browser, so their layers are only checked for a volume_id.

Raises traitlets.TraitError: For a missing or dangling volume reference.

StructureWidget

source

MatterViz widget for visualizing structures in Python notebooks.

Structure data can be provided as:

  • structure: A parsed dict (from pymatgen/ASE .as_dict()), or a pymatgen Structure/ASE Atoms object (auto-converted).
  • structure_string: A raw file string (CIF, POSCAR, XYZ, etc.) parsed on the frontend. Useful when you have the file content but not a parsed object. If both are provided, structure takes precedence.

volumetric_data entries hold memoryview buffers, so to_dict() isn't plain JSON. Custom bundles must support matterviz-binary-v1. Contiguous float32 input grids are borrowed and must stay unmodified.

Examples Basic usage: >>> from pymatviz import StructureWidget >>> structure_data = {...} # Structure dictionary from pymatgen/ASE >>> widget = StructureWidget(structure=structure_data)

With custom visualization options:
>>> widget = StructureWidget(
...     structure=structure_data,
...     atom_radius=0.8,
...     show_bonds=True,
...     color_scheme="Jmol",
...     style="border-radius: 10px; width: 100%; height: 600px;",
... )

Site vectors (force/magmom/spin) are auto-detected from site properties.
Single vector keys use element-colored arrows; multiple keys get palette
colors with per-key toggles, scale sliders, and origin gap control:
>>> StructureWidget(structure=struct_with_forces)  # auto-detected
>>> StructureWidget(structure=struct, vector_origin_gap=0.3)  # multi-method
>>> StructureWidget(structure=struct, vector_normalize=True)  # direction only
  • Isosurfaces: pymatgen VolumetricData objects or dicts plus explicit layers (isovalue in the volume's units, e/ų for CHGCAR) that pick their volume by volume_id (a pymatgen data key, or a dict's id/label):

    layer = dict(isovalue=0.05, color="#3b82f6", opacity=0.6, visible=True) layer |= dict(volume_id="total") StructureWidget( ... volumetric_data=[Chgcar.from_file("CHGCAR")], ... isosurface_settings={"layers": [layer], "wireframe": False, "halo": 0}, ... )

    Several pymatgen volumes share data keys (every Chgcar has "total"), so pass a {prefix: volume} mapping to namespace ids (and labels) as "prefix/key":

    volumes = {"relaxed": chgcar_relaxed, "initial": chgcar_initial} layer |= dict(volume_id="relaxed/total") StructureWidget( ... volumetric_data=volumes, isosurface_settings={"layers": [layer]} ... )

module pymatviz.widgets.sunburst

SunburstWidget

source

Show a hierarchy as concentric rings or stacked icicle rows.

Set data to a node or list of root nodes. Nodes support id, label, value, children, color, pattern and metadata. Clicking a branch updates zoom_root_id; assign an ID to zoom from Python.

Examples >>> from pymatviz import SunburstWidget >>> SunburstWidget(data=[{"label": "Fe-O", "value": 4}], shape="icicle")

module pymatviz.widgets.trajectory

TrajectoryWidget

source

MatterViz widget for visualizing molecular dynamics and geometry optimization trajectories in Python notebooks.

Accepts trajectory data directly (list of structures, dict with frames) or a data_url the frontend fetches and parses itself (XYZ/extXYZ, ASE .traj, XDATCAR, LAMMPS dump, pymatgen Trajectory JSON; .gz/.zip compressed). A binary trajectory holds memoryview buffers, so to_dict() isn't plain JSON (json.dumps needs a default for them).

Examples Basic usage with list of structures: >>> from pymatviz import TrajectoryWidget >>> trajectory_data = [...] # List of structures >>> widget = TrajectoryWidget(trajectory=trajectory_data) >>> widget

With per-frame properties (scalars are plotted; per-atom ``forces`` of shape
(n_sites, 3) are drawn as vectors with their max/RMS norms plotted):
>>> trajectory_with_props = [
...     {"structure": struct1, "energy": -1.23, "forces": forces1},
...     {"structure": struct2, "energy": -1.25, "forces": forces2},
... ]
>>> widget = TrajectoryWidget(trajectory=trajectory_with_props)

A pymatgen ``Trajectory`` (or its ``as_dict()``) is parsed by the frontend:
>>> widget = TrajectoryWidget(trajectory=Trajectory.from_file("XDATCAR"))

With custom visualization options:
>>> widget = TrajectoryWidget(
...     trajectory=trajectory_data,
...     display_mode="structure+plot",
...     plot_type="distribution",
...     layout="horizontal",
...     show_controls=True,
...     auto_play=True,
...     style="height: 600px; border: 2px solid blue;",
... )

With local file path (automatically detected and loaded):
>>> widget = TrajectoryWidget(data_url="path/to/trajectory.xyz")
>>> widget = TrajectoryWidget(data_url="path/to/trajectory.h5")

LAMMPS dumps only carry integer atom types; name them with atom_type_mapping:
>>> widget = TrajectoryWidget(
...     data_url="path/to/dump.lammpstrj", atom_type_mapping={1: "Si", 2: "O"}
... )

module pymatviz.widgets.treemap

TreemapWidget

source

MatterViz widget for zoomable treemap charts of hierarchical data.

Data is a nested node dict (or list of root nodes) with plotly-like semantics: {"label": ..., "value": ..., "children": [...]} plus optional id, color, pattern, and metadata keys. Clicking a cell zooms into it (breadcrumb pathbar zooms back out); zoom_root_id syncs both ways: zooming in the UI notifies Python and setting it from Python re-roots the view (None = data root).

Examples >>> from pymatviz import TreemapWidget >>> nodes = {"label": "systems", "children": [{"label": "Li-Fe-O", "value": 4}]} >>> widget = TreemapWidget(data=nodes)

module pymatviz.widgets.xrd

XrdWidget

source

MatterViz widget for visualizing X-ray diffraction patterns.

Accepts a pymatgen DiffractionPattern or a dict with either:

  • canonical keys: x (2-theta), y (intensity), optional hkls/d_hkls/kind
  • Ferrox keys: two_theta, intensities, optional hkls/d_spacings/kind

Patterns without hkls are treated as measured scans (kind="profile"): drawn as a line and never broadened. Pass kind="sticks" to force bar rendering.

Examples From a pymatgen DiffractionPattern: >>> from pymatviz import XrdWidget >>> widget = XrdWidget(patterns=diffraction_pattern) >>> widget

From a dict:
>>> data = {"x": two_theta, "y": intensities, "hkls": hkl_list}
>>> widget = XrdWidget(patterns=data)

With custom options:
>>> widget = XrdWidget(
...     patterns=diffraction_pattern,
...     style="height: 400px;",
... )

module pymatviz.xrd

format_hkl(hkl: tuple[int, int, int], format_type: HklFormat) -> str

source

Format hkl indices as a string.

Args

  • hkl (tuple[int, int, int]): The hkl indices to format.
  • format_type ('compact' | 'full' | None): How to display the hkl indices.

Raises

  • ValueError: If format_type is not one of 'compact', 'full', or None.

xrd_pattern(patterns: PatternOrStruct | Mapping[str, PatternOrStruct | tuple[PatternOrStruct, dict[str, Any]]], *, peak_width: float=0.5, annotate_peaks: float=5, hkl_format: HklFormat=HklCompact, show_angles: bool | None=None, wavelength: float=cu_k_alpha_wavelength, stack: Literal['horizontal', 'vertical'] | None=None, subplot_kwargs: dict[str, Any] | None=None, subtitle_kwargs: dict[str, Any] | None=None, axis_title_kwargs: dict[str, Any] | None=None) -> go.Figure

source

Plot XRD patterns from DiffractionPattern, pymatgen Structure, or ASE Atoms objects, individually or in a mapping.

Args patterns (PatternOrStruct | dict[str, PatternOrStruct | tuple[PatternOrStruct, dict[str, Any]]]): Either a single DiffractionPattern or Structure object, or a dictionary where keys are legend labels and values are either DiffractionPattern/Structure objects or tuples of (DiffractionPattern/Structure, kwargs) for customizing individual patterns.

  • peak_width (float): Width of the diffraction peaks in degrees. Default is 0.5.
  • annotate_peaks (float): Controls peak annotation. If int, annotates that many highest peaks. If float, should be in (0, 1) which will annotate peaks higher than that fraction of the highest peak. Default is 5.
  • hkl_format (HklFormat): Format for hkl indices. One of 'compact' (ex: '100'), 'full' (ex: '(1, 0, 0)'), or None for no hkl indices. Default is 'compact'.
  • show_angles (bool | None): Whether to show angles in peak annotations. If None, it will default to True if plotting 1 or 2 patterns, False for 3 or more patterns.
  • wavelength (float): X-ray wavelength for the XRD calculation (in Angstroms). Default is 1.54184 (Cu K-alpha). Only used if patterns argument contains Structures.
  • stack ("horizontal" | "vertical" | None): If set to "horizontal" or "vertical", creates separate subplots for each pattern. Default is None (all patterns in one plot).
  • subplot_kwargs (dict[str, Any] | None): Passed to make_subplots. Can be used to control spacing between subplots, e.g. {'vertical_spacing': 0.02}.
  • subtitle_kwargs (dict[str, Any] | None): Override default subplot title settings. E.g. dict(font_size=14). Default is None.
  • axis_title_kwargs (dict[str, Any] | None): Override default axis title settings. E.g. dict(font_size=14). Default is None.

Raises

  • ValueError: If patterns are empty, intensities cannot be normalized, or annotate_peaks is not a nonnegative int or a float in (0, 1).
  • TypeError: If patterns is not a DiffractionPattern, Structure, ASE Atoms, or a mapping of them.

Returns go.Figure: A plotly figure of the XRD pattern(s).