Skip to content

[Bug]: Colorbar does not work for negative values with contour/contourf #21882

@sodlr

Description

@sodlr

Bug summary

The colorbar does not work with contour/contourf, if the data contains negative values AND zeros.
The error message is the following:

matplotlib/transforms.py:2663: RuntimeWarning: divide by zero encountered in double_scalars
y_scale = 1.0 / inh
matplotlib/transforms.py:2665: RuntimeWarning: invalid value encountered in double_scalars
[0.0 , y_scale, (-inb*y_scale)]

It does work for only negative (without zero), only positive (without zero), and mixed positive and negative values.
The colorbar also works with imshow regardless of the data.

Code for reproduction

import matplotlib.pyplot as plt
import numpy as np

# mixed positive and negative values work
data = np.arange(-5, 4).reshape((3,3))

fig, ax = plt.subplots()
im = ax.contourf(data)
cb = plt.colorbar(im)

# negative and zero does not work!
data = np.arange(-5, 4).reshape((3,3))
vmax = np.max(data)
data -= vmax

fig, ax = plt.subplots()
im = ax.contourf(data)
cb = plt.colorbar(im)

Actual outcome

First example that works!

Figure 2021-12-08 161957

Second example that does not work!

Figure 2021-12-08 162009

Expected outcome

The same plot as the first example with a colorbar from 0 to -9, which is produced with matplotlib 3.4.3.

Additional information

No response

Operating system

No response

Matplotlib Version

3.5.0

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions