Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tick frequency on X (time, not number) frequency in matplotlib

My python plot data only show 2 points on x axis.

I would like to have more, but 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 only shows 2 points of interval. I tried to use .xticks but didn't work for X axis. It gave the below error:

TypeError: object of type 'datetime.datetime' has no len() 
like image 672
Kensg Avatar asked Aug 27 '14 23:08

Kensg


People also ask

How do I change the X tick frequency in MatPlotLib?

Setting Figure-Level Tick Frequency in Matplotlib You can use the xticks() and yticks() functions and pass in an array denoting the actual ticks. On the X-axis, this array starts on 0 and ends at the length of the x array. On the Y-axis, it starts at 0 and ends at the max value of y .

How do you change Yticks in MatPlotLib?

To create a list of ticks, we will use numpy. arange(start, stop, step) with start as the starting value for the ticks, stop as the non-inclusive ending value and step as the integer space between ticks. Below example illustrate the matplotlib.

How do you change the axis interval in Python?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.


1 Answers

Whatever reason it is you are getting 2 ticks only by default, you can fix it (customise it) by changing the ticker locator using a 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 it in the documentation:

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

But maybe this example will help more:

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

like image 106
Sebastian Avatar answered Sep 19 '22 20:09

Sebastian