Skip to content

[Bug]: Incorrect X-axis scaling with date values #28341

Closed

Description

@pm13

Bug summary

In matplotlib 3.9.0, when plotting dates on the X-axis, calling axhspan unexpectedly expands the X-axis range from 1970 to 2024. This behavior did not occur in version 3.8.4, where the X-axis correctly ranges from 2020 to 2024.

Code for reproduction

import datetime
import matplotlib.pyplot as plt

x = [datetime.date(year, 1, 1) for year in range(2020, 2024)]
y = range(4)

plt.plot(x, y)
plt.axhspan(1, 2)

Actual outcome

3 9 0

Expected outcome

3 8 4

Additional information

No response

Operating system

Fedora

Matplotlib Version

3.9.0

Matplotlib Backend

inline or Agg

Python version

3.12.3

Jupyter version

4.2.1

Installation

pip

Activity

  1. timhoffm commented on Jun 4, 2024

    @timhoffm
    Member

    This is a regression in 3.9.

  2. ksunden commented on Jun 4, 2024

    @ksunden
    Member

    Most likely related to #26788

  3. QuLogic commented on Jun 4, 2024

    @QuLogic
    Member

    A bisect does indeed point to that commit; I'm a bit confused though as it seems like that change is supposed to try and avoid changing the datalimits, but maybe it's something to do with using date/units.

    cc @anntzer

  4. anntzer commented on Jun 5, 2024

    @anntzer
    Contributor

    Woops. The fix is easy:

    diff --git i/lib/matplotlib/axes/_axes.py w/lib/matplotlib/axes/_axes.py
    index 9a2b367fb5..7efbd6562f 100644
    --- i/lib/matplotlib/axes/_axes.py
    +++ w/lib/matplotlib/axes/_axes.py
    @@ -1028,7 +1028,7 @@ class Axes(_AxesBase):
             # For Rectangles and non-separable transforms, add_patch can be buggy
             # and update the x limits even though it shouldn't do so for an
             # yaxis_transformed patch, so undo that update.
    -        ix = self.dataLim.intervalx
    +        ix = self.dataLim.intervalx.copy()
             mx = self.dataLim.minposx
             self.add_patch(p)
             self.dataLim.intervalx = ix

    (intervalx is an array and thus vulnerable to getting mutated in place). Note that axvspan already has the necessary copy() call, only axhspan was missing it.
    Can you take over the patch?

  5. added this to the v3.9.1 milestone on Jul 3, 2024
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

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions