Thanks to visit codestin.com
Credit goes to github.com

Skip to content

3D surface example bug for non-square grid #19171

Closed
@ufmayer

Description

@ufmayer

Bug report

Bug summary

The code in examples/mplot3d/surface3d_3.py fails if xlen != ylen because x, y are switched in the computation of the colors.

Code for reproduction

# https://github.com/matplotlib/matplotlib/blob/master/examples/mplot3d/surface3d_3.py
# Latest commit 73d51ad on Aug 30

"""
=========================
3D surface (checkerboard)
=========================
Demonstrates plotting a 3D surface colored in a checkerboard pattern.
"""

import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator
import numpy as np


ax = plt.figure().add_subplot(projection='3d')

# Make data.
# X = np.arange(-5, 5, 0.25)
# changed range end from 5 to 7 to make X different length from Y
X = np.arange(-5, 7, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

# Create an empty array of strings with the same shape as the meshgrid, and
# populate it with two colors in a checkerboard pattern.
colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
    for x in range(xlen):
        # this fails if X and Y have different shape
        colors[x, y] = colortuple[(x + y) % len(colortuple)]
        # should be:
        # colors[y, x] = colortuple[(x + y) % len(colortuple)]

# Plot the surface with face colors taken from the array we made.
surf = ax.plot_surface(X, Y, Z, facecolors=colors, linewidth=0)

# Customize the z axis.
ax.set_zlim(-1, 1)
ax.zaxis.set_major_locator(LinearLocator(6))

plt.show()

Actual outcome

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-3-787b568e2b6c> in <module>
     34     for x in range(xlen):
     35         # this fails if X and Y have different shape
---> 36         colors[x, y] = colortuple[(x + y) % len(colortuple)]
     37         # should be:
     38         # colors[y, x] = colortuple[(x + y) % len(colortuple)]

IndexError: index 40 is out of bounds for axis 0 with size 40

Expected outcome

Matplotlib version

  • Operating system: Not relevant
  • Matplotlib version: 3.3.2, code is from github commit 73d51ad on Aug 30, 2020
  • Matplotlib backend (print(matplotlib.get_backend())): Not relevant
  • Python version: 3.7.9
  • Jupyter version (if applicable): Not relevant
  • Other libraries:

conda

default

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocumentationGood first issueOpen a pull request against these issues if there are no active ones!

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions