Changing tick frequency at frequency X (time, not number) in matplotlib

In my python data, only 2 points are displayed on the x axis.

I would like to have more, but I don’t know how.

 x = [ datetime.datetime(1900,1,1,0,1,2), datetime.datetime(1900,1,1,0,1,3), ... ] # ( more than 1000 elements ) y = [ 34, 33, 23, ............ ] plt.plot( x, y ) 

The X axis shows only 2 interval points. I tried using .xticks but did not work for the X axis. This gave the error below:

 TypeError: object of type 'datetime.datetime' has no len() 
+6
source share
2 answers

Whatever the reason, you get only 2 ticks by default, you can fix it (configure) by changing the ticker locator using the date locator.

 import matplotlib.pyplot as plt import matplotlib.dates as mdates x = [ datetime.datetime(1900,1,1,0,1,2), datetime.datetime(1900,1,1,0,1,3), ... ] # ( more than 1000 elements ) y = [ 34, 33, 23, ............ ] fig = plt.figure() ax = fig.add_subplot(1,1,1) plt.plot( x, y ) ax.xaxis.set_major_locator(mdates.MinuteLocator(interval=15)) #to get a tick every 15 minutes ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) #optional formatting 

You have several locators (for example: DayLocator, WeekdayLocator, MonthLocator, etc.) read about this in the documentation:

http://matplotlib.org/api/dates_api.html

But perhaps this example will help more:

http://matplotlib.org/examples/api/date_demo.html

+11
source
 plt.plot( matplotlib.dates.date2num( x ), y ) # matplotlib needs float-s, not <datetime.datetime> instances 
-1
source

Source: https://habr.com/ru/post/974438/


All Articles