matplotlib/matplotlib · error · ValueError

margin must be greater than -0.5

Error message

margin must be greater than -0.5

What it means

set_xmargin(m) pads the x data interval by m times the interval on each end before autoscaling. A margin of m <= -0.5 shrinks the resulting span to (1 + 2m) <= 0, i.e. zero or negative width, which cannot define usable view limits, so matplotlib raises this ValueError. Valid values are any float strictly greater than -0.5.

Source

Thrown at lib/matplotlib/axes/_base.py:2829

        the data range instead of expanding it.

        For example, if your data is in the range [0, 2], a margin of 0.1 will
        result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
        of [0.2, 1.8].

        Parameters
        ----------
        m : float greater than -0.5

        See Also
        --------
        :ref:`autoscale_margins`
        matplotlib.axes.Axes.margins
        matplotlib.axes.Axes.get_xmargin

        """
        if m <= -0.5:
            raise ValueError("margin must be greater than -0.5")
        self._xmargin = m
        self._request_autoscale_view("x")
        self.stale = True

    def set_ymargin(self, m):
        """
        Set padding of Y data limits prior to autoscaling.

        *m* times the data interval will be added to each end of that interval
        before it is used in autoscaling.  If *m* is negative, this will clip
        the data range instead of expanding it.

        For example, if your data is in the range [0, 2], a margin of 0.1 will
        result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range
        of [0.2, 1.8].

        Parameters
        ----------

View on GitHub (pinned to b379c1b69e)

Solutions

  1. Keep m strictly greater than -0.5; use small negatives like -0.1 to trim 10% off each end of the data range.
  2. For zero padding use ax.margins(x=0) instead of trying to negate padding.
  3. For arbitrary limits, skip margins and call ax.set_xlim directly.

Example fix

# before
ax.set_xmargin(-0.6)

# after
ax.set_xmargin(-0.1)  # trims 10% from each end
# or
ax.margins(x=0)
Defensive patterns

Strategy: validation

Validate before calling

def safe_xmargin(m):
    if not (m > -0.5):
        raise ValueError('x margin must be > -0.5')
    return m

ax.set_xmargin(safe_xmargin(m))

Prevention

When it happens

Trigger: ax.set_xmargin(-0.6); indirectly ax.margins(x=-0.6) or ax.margins(-0.6); margin values loaded from config files or computed from data that fall outside (-0.5, inf).

Common situations: Using negative margins to clip into the data range via autoscaling; dynamically computed margins (e.g. -0.5 - epsilon from floating-point arithmetic or user sliders) crossing the boundary.

Related errors


AI-assisted analysis of matplotlib/matplotlib@b379c1b69e (2026-08-21). Data as JSON: /api/errors/1b58af9da86d9435. Report an issue: GitHub.