Skip to content
Advertisement

How can I display dates on the x axis in matplotlib?

I have daily data from 1994 Jan 1st – 2000 April 30th. I have the dates in datetime format, but when I plot a line plot with time on the x axis and the variable on the y axis, matplotlib prints out way too much on the x axis. How do I fix this issue with plotting dates?

I have done this so far:

JavaScript

enter image description here

How do I plot the dates so you can see the xticks?

Advertisement

Answer

Let’s start from necessary imports:

JavaScript

The first thing to correct is the way you create your source data:

  1. Use Pandas instead of Numpy (although some Numpy methods are still needed).
  2. Since Pandas has its native date/time type (datetime64), use just it, instead of plain pythoninc datetime.
  3. Create the source data as pandasonic Series.

You can achieve it the following way:

JavaScript

Then a remark concerning the image: Since you have daily data, you should print only every n-th point, e.g. s[::20]. Otherwise the image will be not readable.

And to get image with dates, you can run e.g.:

JavaScript

Things to note:

  • Major x ticks (years) are printed in this case by default.
  • I added minor x ticks (quarters) calling set_minor_locator.
  • Rotation of x labels is not required, but I thought it is a nice feature. If you don’t agree, remove plt.xticks(rotation=30) from the above code.

For the above source data I got the following image:

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement