Skip to content

[Bug]: Line3D.draw requires .shape on _verts3d, but set_data_3d accepts and stores any array-like #32127

Closed

Description

@thc1006

Bug summary

Line3D.set_data_3d documents its parameters as array-like and accepts anything iterable, storing the arguments verbatim in _verts3d. Line3D.draw then reads self._verts3d[0].shape, so a list, which is array-like and passes the setter's own check, raises AttributeError during draw.

The .shape access lives inside if np.any(scale_mask):, so it is only reached when a coordinate is invalid for the current axis scale. A finite list draws fine, which is why this can sit unnoticed for a long time and then surface the first time a NaN appears.

This is new in 3.11. 3.10.9 has no such branch and draws the same input.

Code for reproduction

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(projection="3d")
(line,) = ax.plot([0.0], [0.0], [0.0])

line.set_data_3d([float("nan")], [float("nan")], [float("nan")])
fig.canvas.draw()

Actual outcome

Traceback (most recent call last):
  ...
  File ".../mpl_toolkits/mplot3d/art3d.py", line 363, in draw
    (len(self._verts3d), *self._verts3d[0].shape)
                          ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'shape'

Expected outcome

The figure draws, as it does on 3.10.9 and as it does on 3.11.1 when the same values are passed as arrays:

import numpy as np
line.set_data_3d(np.array([np.nan]), np.array([np.nan]), np.array([np.nan]))
fig.canvas.draw()   # fine

Additional information

The two sides disagree about what _verts3d holds.

set_data_3d checks only that each argument is iterable and stores them as given:

for name, xyz in zip('xyz', args):
    if not np.iterable(xyz):
        raise RuntimeError(f'{name} must be a sequence')
self._verts3d = args

draw requires them to have .shape:

if np.any(scale_mask):
    mask = np.broadcast_to(
        scale_mask,
        (len(self._verts3d), *self._verts3d[0].shape)
    )

Behaviour by input and version:

coordinates _verts3d holds 3.10.9 3.11.1
finite lists draws draws
NaN lists draws AttributeError
NaN arrays draws draws

The narrowest fix is np.shape(self._verts3d[0]) in draw, which leaves what get_data_3d() returns unchanged. Converting in the setter also works but changes the stored type, so a caller that reads back what it passed would see something different. I have both verified locally and am happy to open a PR for the first.

Worth noting because it is how this was found: #22308 recommended set_data([a], [b]) followed by set_3d_properties([c]) as the way to update a Line3D, which produces exactly this state. Code written against that advice draws on 3.10 and raises on 3.11 as soon as a coordinate goes non-finite.

Operating system

Linux (Debian 13, kernel 6.12)

Matplotlib Version

3.11.1 (3.10.9 unaffected; the branch is present on main)

Matplotlib Backend

Agg

Python version

3.14

Jupyter version

N/A

Installation

pip

Activity

  1. thc1006 commented on Jul 28, 2026

    @thc1006
    Author

    Some more digging, since "new in 3.11" was not a precise enough description of where this came from or how wide it is.

    Where the requirement came from

    It arrived in two steps, and the second is what made it reachable by default.

    d18c52b "fix Line3D masking" (Jan 2025) reworked Line3D.draw to build a mask and broadcast it, which is where _verts3d[0].shape first appears:

             if self._axlim_clip:
    -            mask = _viewlim_mask(*self._verts3d, self.axes)
    +            mask = np.broadcast_to(
    +                _viewlim_mask(*self._verts3d, self.axes),
    +                (len(self._verts3d), *self._verts3d[0].shape)
    +            )

    At that point the whole block sat behind if self._axlim_clip:, an opt-in argument, so the new requirement only applied to lines that had asked for clipping.

    629d396 "Ignore data on 3D plots that are outside the valid axis scale range" then added _scale_invalid_mask, which runs unconditionally, and changed the guard:

    +        scale_mask = _scale_invalid_mask(*self._verts3d, self.axes)
             if self._axlim_clip:
    +            scale_mask = scale_mask | _viewlim_mask(*self._verts3d, self.axes)
    +        if np.any(scale_mask):
                 mask = np.broadcast_to(
    -                _viewlim_mask(*self._verts3d, self.axes),
    +                scale_mask,
                     (len(self._verts3d), *self._verts3d[0].shape)
                 )

    So the .shape access moved from behind an opt-in flag to behind "any coordinate is invalid for its scale". Nothing about set_data_3d changed; the block that consumes what it stores did.

    Worth noting that _scale_invalid_mask documents its own parameters as array-like, and the caller then requires .shape on the same values.

    3.10.9 has neither: _viewlim_mask returned the masked coordinates directly and there was no broadcast. All the cases below draw there.

    What actually triggers it

    Not only NaN. Anything that makes the mask truthy, on 3.11.1 with _verts3d holding lists:

    condition result
    NaN, linear scale AttributeError
    inf, linear scale AttributeError
    <= 0 on a log scale AttributeError
    out of view with axlim_clip=True AttributeError
    all finite, linear scale draws

    The third row is the one I would highlight. _scale_invalid_mask was added so that 3D data outside a scale's valid domain is ignored rather than breaking the plot. On a Line3D whose coordinates were set as lists, it raises instead, so the feature does not survive its own motivating case.

    Tuples fail the same way, with 'tuple' object has no attribute 'shape'.

    How wide

    I went through every user of _scale_invalid_mask / _viewlim_mask in art3d.py and exercised each through its public entry point with list input and a triggering coordinate:

    class public path 3.11.1
    Line3D set_data_3d(list) raises
    Line3D set_data(list) + set_3d_properties(list) raises
    Line3D ax.plot(list) draws
    Line3DCollection Line3DCollection(list of lists) draws
    Poly3DCollection Poly3DCollection(list verts) draws
    Path3DCollection ax.scatter(list) draws
    Text3D ax.text(nan, ...) draws
    Axes3D plot_surface with NaN draws

    Everything that goes through a high-level API converts to arrays on the way in, which is why this is not more visible. The two Line3D setters are the exception: they are the documented way to update an existing 3D line in place, and they store what they are handed.

    Path3DCollection.do_3d_projection has the identical self._offsets3d[0].shape one screen down. Assigning _offsets3d a tuple of lists directly reproduces the same error, but that attribute is private and its public writer routes through juggle_axes with get_offsets(), so I have not counted it as a public-API break. Happy to include it in #32128 if you would rather the two were consistent.

    Fix

    #32128 uses np.shape(self._verts3d[0]), which accepts both and leaves what get_data_3d() returns unchanged. Verified against a released 3.11.1 with only art3d.py swapped: the new test fails before and passes after, and the rest of test_art3d.py stays green.

  2. mohit-sharma-001 commented on Jul 29, 2026

    @mohit-sharma-001

    @thc1006 i would like to view this issue more
    I am willing to take this issue

  3. thc1006 commented on Jul 29, 2026

    @thc1006
    Author

    @thc1006 i would like to view this issue more I am willing to take this issue

    I am doing now u can see already have a PR.

  4. ShamikOfficial commented on Sep 5, 2026

    @ShamikOfficial
    Contributor

    Working on a fix for this — coercing the coordinates to arrays in set_data_3d so draw can safely use .shape.

  5. chirayu08 commented on Sep 8, 2026

    @chirayu08

    Use this change in mpl_toolkits/mplot3d/art3d.py:

    if np.any(scale_mask):
    mask = np.broadcast_to(
    scale_mask,
    (len(self._verts3d), *np.shape(self._verts3d[0]))
    )

    The important part is changing:

    self._verts3d[0].shape

    to:

    np.shape(self._verts3d[0])
    Why this is the better fix

    It preserves the existing behavior of:

    line.get_data_3d()

    because you're not changing what set_data_3d() stores.

    You're simply making draw() consistent with the setter's documented support for array-like/iterable inputs.

    Before opening the PR

    I'd add a regression test. Look for the existing Line3D tests, probably under something like:

    lib/mpl_toolkits/mplot3d/tests/

    Search for:

    set_data_3d

    Then add a test covering the exact failure:

    line.set_data_3d([np.nan], [np.nan], [np.nan])
    fig.canvas.draw()

    Ideally test lists, because that's the regression:

    def test_line3d_set_data_list_with_nan():
    fig = plt.figure()
    ax = fig.add_subplot(projection="3d")
    (line,) = ax.plot([0.0], [0.0], [0.0])

    line.set_data_3d([np.nan], [np.nan], [np.nan])
    fig.canvas.draw()
    

    Follow the existing Matplotlib test style rather than blindly copying this exact test.

    Then run the relevant tests

    From the Matplotlib repository:

    python -m pytest lib/mpl_toolkits/mplot3d/tests/

    If that's too broad, first locate the relevant test file and run just that file:

    python -m pytest path/to/test_file.py

    Then run the specific test:

    python -m pytest path/to/test_file.py -k line3d
    Your PR should be small

    Ideally your PR contains only:

    art3d.py
    ↓
    np.shape(...) fix

    test file
    ↓
    regression test

    Don't modify unrelated formatting or refactor other code.

  6. added this to the v3.12.0 milestone on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions