Skip to content

[Bug]: matplotlib.axes.Axes.fill_between() doesn't work correctly when parameter x is not sorted #23107

Description

@fantauzzi

Bug summary

When calling Axes.fill_between(x, y1, y2, where, interpolate, step, *, data, **)
with argument x whose items are not in ascending or descending order, the method colors the required area in a wrong way.

Code for reproduction

import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)

# Shuffle the content of x and y1 in a coordinated way
shuffle_me = list(zip(x, y1))
np.random.shuffle(shuffle_me)
x = np.array([item for item, _ in shuffle_me])
y1 = np.array([item for _, item in shuffle_me])
# This makes a bad plot
_, ax = plt.subplots()
ax.fill_between(x, y1)

# Sort the content of x and y1 in a coordinated way, such that x is in ascending order
y1 = y1[x.argsort()]
x = np.sort(x)
# This makes a good plot
_, ax = plt.subplots()
ax.fill_between(x, y1)

plt.pause(0)

Actual outcome

Screenshot from 2022-05-23 17-28-39

Expected outcome

Screenshot from 2022-05-23 17-29-14

Additional information

The issue is systematic.

Operating system

Ubuntu 20.04

Matplotlib Version

3.5.2

Matplotlib Backend

TkAgg

Python version

3.8.10

Jupyter version

N/A

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions