matplotlib how to specify time locator's start-ticking timestamp?

前端 未结 2 951
耶瑟儿~
耶瑟儿~ 2021-02-01 11:10

All I want is quite straight forward, I just want the locator ticks to start at a specified timestamp:
peudo code: locator.set_start_ticking_at( datetime_dummy )

2条回答
  •  清歌不尽
    2021-02-01 11:57

    @unutbu: Many thanks: I've been looking everywhere for the answer to a related problem!

    @eliu: I've adapted unutbu's excellent answer to demonstrate how you can define lists (to create different 'dateutil' rules) which give you complete control over which x-ticks are displayed. Try un-commenting each example below in turn and play around with the values to see the effect. Hope this helps.

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')
    df = pd.Series(np.random.randn(len(idx)),  index = idx)
    fig, ax = plt.subplots()
    
    # Choose which major hour ticks are displayed by creating a 'dateutil' rule e.g.:
    
    # Only use the hours in an explicit list:
    # hourlocator = mdates.HourLocator(byhour=[6,12,8])
    
    # Use the hours in a range defined by: Start, Stop, Step:
    # hourlocator = mdates.HourLocator(byhour=range(8,15,2))
    
    # Use every 3rd hour:
    # hourlocator = mdates.HourLocator(interval = 3)
    
    # Set the format of the major x-ticks:
    majorFmt = mdates.DateFormatter('%H:%M')  
    
    ax.xaxis.set_major_locator(hourlocator)
    ax.xaxis.set_major_formatter(majorFmt)
    
    #... and ditto to set minor_locators and minor_formatters for minor x-ticks if needed as well)
    
    ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)
    
    fig.autofmt_xdate() # optional: makes 30 deg tilt on tick labels
    
    plt.show()
    

提交回复
热议问题