1

I'm having trouble limiting the number of dates on the x-axis to make them legible. I need to plot the word length vs the year but the number of years is too large for the plot size.

The Issue:

enter image description here

Any help is appreciated.

Cryoexn
  • 97
  • 1
  • 1
  • 8

1 Answers1

2

As mentioned in the comments, use datetime (if your dates are in string format, you can easily convert them to datetime). Once you do that it should automatically display years along the x-axis. If you need to change the frequency of ticks to every year (or anything else), you can use mdates, like so:

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import datetime
import math

start = datetime.datetime.strptime("01-01-2000", "%d-%m-%Y")
end = datetime.datetime.strptime("10-04-2019", "%d-%m-%Y")

x = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
y = [math.sqrt(x) for x in range(len(x))]

fig, ax = plt.subplots()
ax.plot(x, y)
ax.xaxis.set_major_locator(mdates.YearLocator())
fig.autofmt_xdate()
plt.show()

The snippet above generates the following: enter image description here

kimalser
  • 303
  • 1
  • 4
  • 10
  • How do I change the timedelta to years. I'm getting `ValueError: x and y must have same first dimension, but have shapes (13879,) and (39,)` – Cryoexn Oct 04 '19 at 23:45
  • @Cryoexn, the x and y arrays in my code are just dummy data for the demo. You should use whatever data you were using, except convert the time array into an array of datetime objects. Does it make sense? – kimalser Oct 05 '19 at 04:10
  • Yeah I got the date time working with my data now, but I'm still having trouble getting the date time to only show the years. I couldn't find how to do it on the internet. – Cryoexn Oct 06 '19 at 13:20
  • Try using `mdates.YearLocator()` similar to how I did it in the code snippet. – kimalser Oct 06 '19 at 18:07
  • I have that in my code as you did in the example `ax.xaxis.set_major_locator(mdates.YearLocator())` – Cryoexn Oct 06 '19 at 20:35
  • I looked around for other ways to get the date formatted and added the line `ax.xaxis.set_major_formatter(m_dates.DateFormatter('%Y'))` and now I have a more favorable result than what I had started with. Thank you very much for the help and guidance! – Cryoexn Oct 06 '19 at 20:42
  • Yay! Welcome :) – kimalser Oct 07 '19 at 05:03