Explain Codes LogoExplain Codes Logo

Date ticks and rotation

python
matplotlib
plotting
date-ticks
Alex KataevbyAlex Kataev·Dec 8, 2024
TLDR

Rotate date ticks in your Matplotlib charts swiftly with autofmt_xdate() for a quick fix or rotation parameter in plt.xticks() for a hands-on approach. Here's how:

import matplotlib.pyplot as plt # ...[plotting magic goes here]... plt.gcf().autofmt_xdate() # For the lazy coder # Or: plt.xticks(rotation=45) # For the precision seeker plt.show()

autofmt_xdate() is the easy way out as it neatly tilts labels. The rotation parameter in plt.xticks() grants you the power to specify an exact angle. Choose your weapon!

How to rotate without breaking

For a more stable rotation

A spoiler-free way to apply and maintain custom rotation is setp(). Why? Because it's dependable. Here, Python's law of precise language triumphs:

ax = plt.gca() # Getting the compass in hands plt.setp(ax.get_xticklabels(), rotation=45, ha="right") # Rotate & right-align, be sure to do your morning stretches!

Winning over plt.gca()

Although plt.gca() might seem like a lifesaver, it doesn't play nice with multiple axes. And we don't like rude players, do we?

fig, axs = plt.subplots(2, 1) plt.setp(axs[0].xaxis.get_majorticklabels(), rotation=45) # Rotate the first subplot. Because, why not!

Getting the axis right without confusion

In a world where order is critical, simply setting x-ticks before labeling ensures you live without regrets:

ax.set_xticklabels(xlabels, rotation=45) # Setting rotation first, just like eating dessert before dinner!

Minimize confusion for maximum gains

Warding off overlapping labels

Make sure the rotated labels aren't just positioned well, but also look good. After a night of dancing (rotating) they could do with some breathing space:

ax.tick_params(axis='x', pad=15) # "Give me some space!", said the tick

Strong, independent ticks

Using the object-oriented approach, you wave goodbye to errors:

ax.xaxis.set_tick_params(rotation=45) # Ticks like to rotate like independent objects! They don't need no plt.xticks()

Auto-Ticks: Transform your date plots

Use AutoDateLocator and AutoDateFormatter to apply a makeover to your date plots:

from matplotlib.dates import AutoDateLocator, AutoDateFormatter ax.xaxis.set_major_locator(AutoDateLocator()) ax.xaxis.set_major_formatter(AutoDateFormatter(AutoDateLocator()))

Making your plot shine

Strike a balance

Make readers' eyes happy with a subtle rotation:

plt.setp(ax.get_xticklabels(), rotation=20) # A little tilt won’t hurt

A spacious plot is a happy plot

Add some air to your subplot layout:

plt.subplots_adjust(bottom=0.2) # "Let's give ourselves some space!", said Plot to Subplot

Tick alignment mastery

Align ticks with data points, because accuracy is not overrated:

from matplotlib.ticker import MaxNLocator ax.xaxis.set_major_locator(MaxNLocator(integer=True))