Cryoexn
Cryoexn

Reputation: 137

Using matplotlib limit the frequency of the x ticks

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.

Upvotes: 1

Views: 184

Answers (1)

kimalser
kimalser

Reputation: 323

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

Upvotes: 2

Related Questions