Lightning-AI/pytorch-lightning · warning · MisconfigurationException

To use the `plot` method, you must have Matplotlib installed

Error message

To use the `plot` method, you must have Matplotlib installed. Install it by running `pip install -U matplotlib`.

What it means

_lr_find().plot() requires Matplotlib, but the optional dependency is not installed in the environment (Lightning guards the import with _MATPLOTLIB_AVAILABLE). Plotting is optional so the library raises MisconfigurationException with install instructions instead of an ImportError.

Source

Thrown at src/lightning/pytorch/tuner/lr_finder.py:130

        args = (optimizer, self.lr_max, self.num_training)
        scheduler = _LinearLR(*args) if self.mode == "linear" else _ExponentialLR(*args)

        trainer.strategy.optimizers = [optimizer]
        trainer.strategy.lr_scheduler_configs = [LRSchedulerConfig(scheduler, interval="step")]
        _validate_optimizers_attached(trainer.optimizers, trainer.lr_scheduler_configs)

    def plot(
        self, suggest: bool = False, show: bool = False, ax: Optional["Axes"] = None
    ) -> Optional[Union["plt.Figure", "plt.SubFigure"]]:
        """Plot results from lr_find run
        Args:
            suggest: if True, will mark suggested lr to use with a red point
            show: if True, will show figure
            ax: Axes object to which the plot is to be drawn. If not provided, a new figure is created.

        """
        if not _MATPLOTLIB_AVAILABLE:
            raise MisconfigurationException(
                "To use the `plot` method, you must have Matplotlib installed."
                " Install it by running `pip install -U matplotlib`."
            )
        import matplotlib.pyplot as plt

        lrs = self.results["lr"]
        losses = self.results["loss"]

        fig: Optional[Union[plt.Figure, plt.SubFigure]]
        if ax is None:
            fig, ax = plt.subplots()
        else:
            fig = ax.figure

        # Plot loss as a function of the learning rate
        ax.plot(lrs, losses)
        if self.mode == "exponential":
            ax.set_xscale("log")

View on GitHub (pinned to 9fed5c27d2)

Solutions

  1. pip install -U matplotlib
  2. Skip plot() and use the returned results dict / lr_finder.suggestion() programmatically
  3. If installing is impossible, export self.results['lr'] and self.results['loss'] and plot elsewhere

Example fix

# before
lr_finder = tuner.lr_find(model)
lr_finder.plot()  # MisconfigurationException without matplotlib
# after (no plotting needed)
lr_finder = tuner.lr_find(model)
model.hparams.lr = lr_finder.suggestion()
Defensive patterns

Strategy: validation

Validate before calling

try:
    import matplotlib  # noqa: F401
    HAS_MPL = True
except ImportError:
    HAS_MPL = False
if not HAS_MPL:
    lr = lr_finder.suggestion()  # skip plotting
else:
    lr_finder.plot()

Prevention

When it happens

Trigger: Calling lr_finder.plot() (or trainer.tuner.lr_find(model).plot()) in an environment without matplotlib installed — common in slim Docker/CI images.

Common situations: Minimal training-only Docker images, CI pipelines, or cluster environments where matplotlib was never installed because training itself does not need it.

Understand the failure class

Background: "X is not installed. Please install it with pip install Y": missing optional dependency errors — ImportError/ValueError raised when a library's optional extra was never installed — this error's family across 22 libraries.

Related errors


AI-assisted analysis of Lightning-AI/pytorch-lightning@9fed5c27d2 (2026-08-28). Data as JSON: /api/errors/768b6aa1887d2614. Report an issue: GitHub.