Skip to content

[Bug]: Error showing colorbar when contouring a uniform field #23817

Closed
@ianthomas23

Description

@ianthomas23

Bug summary

If you contour a uniform field i.e. ax.contour(z=[[1, 1], [1,1]])) it works fine, although the output is not very interesting. If you add a colorbar to this, you receive an error. Without the colorbar call there is no error.

Code for reproduction

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
cs = ax.contour([[1, 1], [1, 1]])
fig.colorbar(cs, ax=ax)
plt.show()

Actual outcome

bug.py:18: UserWarning: No contour levels were found within the data range.
cs = ax.contour([[1, 1], [1, 1]])
/home/iant/github/matplotlib/lib/matplotlib/colorbar.py:1224: RuntimeWarning: invalid value encountered in divide
y = y / (self._boundaries[self._inside][-1] -
Traceback (most recent call last):
File "bug.py", line 19, in
fig.colorbar(cs, ax=ax)
File "/home/iant/github/matplotlib/lib/matplotlib/figure.py", line 1276, in colorbar
cb = cbar.Colorbar(cax, mappable, **cb_kw)
File "/home/iant/github/matplotlib/lib/matplotlib/_api/deprecation.py", line 384, in wrapper
return func(*inner_args, **inner_kwargs)
File "/home/iant/github/matplotlib/lib/matplotlib/colorbar.py", line 396, in init
self._draw_all()
File "/home/iant/github/matplotlib/lib/matplotlib/colorbar.py", line 535, in _draw_all
X, Y = self._mesh()
File "/home/iant/github/matplotlib/lib/matplotlib/colorbar.py", line 1110, in _mesh
y, _ = self._proportional_y()
File "/home/iant/github/matplotlib/lib/matplotlib/colorbar.py", line 1246, in _proportional_y
automin = yscaled[1] - yscaled[0]
IndexError: index 1 is out of bounds for axis 0 with size 1

Expected outcome

Colorbar should be displayed as normal.

Additional information

Essentially the colorbar data range is zero, so when trying to determine the y-position of a particular contour level there is a divide by zero.

This has probably been a problem for years. It is a silly test case as who wants to contour a uniform field, but we should handle it more gracefully.

Operating system

N/A

Matplotlib Version

3.6.0.dev3132+gf8cf0ee5e7

Matplotlib Backend

N/A

Python version

3.8.10

Jupyter version

N/A

Installation

from source (.tar.gz)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Difficulty: Easyhttps://matplotlib.org/devdocs/devel/contribute.html#good-first-issuesGood first issueOpen a pull request against these issues if there are no active ones!topic: color/colorbar

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions