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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With