Neal Neal - 1 year ago 372
Python Question

Date ticks and rotation in matplotlib

I am having an issue trying to get my date ticks rotated in matplotlib. A small sample program is below. If I try to rotate the ticks at the end, the ticks do not get rotated. If I try to rotate the ticks as shown under the comment 'crashes', then matplot lib crashes.

This only happens if the x-values are dates. If I replaces the variable

with the variable
in the call to
, the
call works just fine inside

Any ideas?

import numpy as np
import matplotlib.pyplot as plt
import datetime as dt

def avail_plot(ax, x, y, label, lcolor):
ax.set_ylabel(label, rotation='horizontal', color=lcolor)


ax2 = ax.twinx()
ax2.plot(x, [1 for a in y], 'b')

f, axs = plt.subplots(2, sharex=True, sharey=True)
t = np.arange(0.01, 5, 1)
s1 = np.exp(t)
start =
for val in t:
next_val = start + dt.timedelta(0,val)
start = next_val

avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
plt.subplots_adjust(hspace=0, bottom=0.3)
#doesn't crash, but does not rotate the xticks

cge cge
Answer Source

Move plt.xticks(rotation=70) to right before the two avail_plot calls, eg

avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')

This sets the rotation property before setting up the labels. Since you have two axes here, I think plt.xticks gets confused after you've made the two plots. It seems that at the point when plt.xticks doesn't do anything, plt.gca() does not give you the axes you want to modify, and so plt.xticks, which acts on the current axes, is not going to work.

Alternatively, for example, not using plt.xticks, you can use

plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )

after the two avail_plot calls.