Option FanaticOptions, stock, futures, and system trading, backtesting, money management, and much more!

Resolving Dates on the X-Axis (Part 2)

Today I conclude with my solution for resolving dates as x-axis tick labels.

I think part of the confusion is that to this point, the x-coordinates of the points being plotted are equal to the x-axis tick labels. This need not be the case, though, and is really not even desired. I want to leave the tick labels as datetime so matplotlib can automatically scale it. This should also allow matplotlib to plot the x-values in the proper place.

Documentation on plt.xticks() reads:

plt dot xticks documentation (6-14-22)

The first segment suggests I can define the tick locations and tick labels with the first two arguments. For now, those are identical. Adding c as the first two arguments in L11 (see Part 1) gives this:

output of code snippet 12 (6-14-22)

Ah ha! Can I now insert a subset as a different time range for the x-coordinates?

output of code snippet 13 (6-14-22)

I think we’re onto something! I commented out the print lines in the interest of space.

Finally, let’s reformat the x-axis labels to something more readable and verify datatype:

Code snippet 14 (6-14-22)

Success! I am able to eliminate hours, minutes, and seconds. Interestingly, the axis labels now show up as string but matplotlib is still able to understand their values and plot the points correctly (I suspect the latter takes place before the former). Changing the date range on the axis helps because this graph should look different from the previous one.

To put in more object-oriented language:

Code snippet 15 (6-17-22)

I suspect the confusion between the plt and fig, ax approaches is widespread. For a better explanation, see here or here.

No comments posted.

Leave a Reply

Your email address will not be published. Required fields are marked *