Skip to content

[Bug]: X-Axis date label not rotated #22521

Closed
@johan162

Description

@johan162

Bug summary

Using a date x-axis that are being autoscaled outside the initial data range due to the added vline then the first (and only the first) data label gets no rotation.

Code for reproduction

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

dates = [datetime.datetime(2022, 2, 21, 0, 0),
         datetime.datetime(2022, 2, 22, 0, 0),
         datetime.datetime(2022, 2, 27, 0, 0)]
data1 = [5,8,12]

fig, ax = plt.subplots(1, 1, figsize=(20/2.54, 12/2.54))
plt.subplots_adjust(left=0.08, bottom=0.15, right=0.95)
plt.title("Date x-axis label angle bug")

b1 = ax.bar(dates, data1, width=0.7)

# Setup the date x-axis in weeks marking start of each week start
ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=mdates.MO))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%a %b %d'))

# The same problem regardless the method to set the angle
#for label in ax.get_xticklabels(which='major'):
#    label.set(rotation=30, horizontalalignment='right')
plt.xticks(rotation=30, ha="right")

# Add a vline to force the auoscaling outside the data range
plt.axvline(x=datetime.datetime(2022, 3, 15, 0, 0))

plt.show()

Actual outcome

As can be seen in the screenshot the Feb 28 label is not rotated.

Screenshot 2022-02-21 at 16 19 12

Expected outcome

That the dates are rotated as in the following screenshot.
Screenshot 2022-02-21 at 16 22 14

Note: As long as the initial dates for the available data extends past Feb 28 then the labels are correctly rotated

Additional information

This seems to occur if the autoscale range is forced outside the initial range (as required by the data) by the addition of annotations and/or vlines outside the original x-axis data span.

Operating system

OSX

Matplotlib Version

3.5.1

Matplotlib Backend

No response

Python version

3.9.10

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions