Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Frequency and rotation of x-axis labels in Matplotlib

I wrote a simple script below to generate a graph with matplotlib. I would like to increase the x-tick frequency from monthly to weekly and rotate the labels. I'm not sure where to start with the x-axis frequency. My rotation line yields an error: TypeError: set_xticks() got an unexpected keyword argument 'rotation'. For the rotation, I'd prefer not to use plt.xticks(rotation=70) as I may eventually build in multiple subplots, some of which should have a rotated axis and some which should not.

import datetime
import matplotlib
import matplotlib.pyplot as plt
from datetime import date, datetime, timedelta

def date_increments(start, end, delta):
    curr = start
    while curr <= end:
        yield curr
        curr += delta

x_values = [[res] for res in date_increments(date(2014, 1, 1), date(2014, 12, 31), timedelta(days=1))]
print len(x_values)
y_values = [x**2 for x in range(len(x_values))]
print len(y_values)
fig = plt.figure()

ax = fig.add_subplot(111)
ax.plot(x_values, y_values)
ax.set_xticks(rotation=70)
plt.show()
like image 909
user2242044 Avatar asked Feb 11 '23 03:02

user2242044


1 Answers

Have a look at matplotlib.dates, particularly at this example.

Tick frequency

You will probably want to do something like this:

from matplotlib.dates import DateFormatter, DayLocator, MonthLocator
days = DayLocator()
months = MonthLocator()

months_f = DateFormatter('%m')

ax.xaxis.set_major_locator(months)
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_major_formatter(months_f)

ax.xaxis_date()

This will plot days as minor ticks and months as major ticks, labelled with the month number.

Rotation of the labels

You can use plt.setp() to change axes individually:

plt.setp(ax.get_xticklabels(), rotation=70, horizontalalignment='right')

Hope this helps.

like image 118
Geotob Avatar answered Feb 27 '23 13:02

Geotob