代码之家  ›  专栏  ›  技术社区  ›  Ahmad ucyo

在Matplotlib中分割x和y标签

  •  3
  • Ahmad ucyo  · 技术社区  · 8 年前

    我有一张以X为日期,Y为读数的图表。X轴的日期间隔为一天。我想要的是在x轴上显示两天之间的小时数(只是在图表中的黄色区域设置小时数)。 该准则的思想是:

    Date=[];Readings=[] # will be filled from another function
    dateconv=np.vectorize(datetime.fromtimestamp)
    Date_F=dateconv(Date)
    ax1 = plt.subplot2grid((1,1), (0,0))
    ax1.plot_date(Date_F,Readings,'-')
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
    ax1.grid(True)
    plt.xlabel('Date')
    plt.ylabel('Readings')
    ax1.set_yticks(range(0,800,50))
    
    plt.legend()
    plt.show()
    

    hours in yellow area

    1 回复  |  直到 8 年前
        1
  •  1
  •   Roald    8 年前

    您可以使用 MultipleLocator 从…起 matplotlib.ticker 具有 set_major_locator set_minor_locator . 请参见示例。

    实例

    import matplotlib.pyplot as plt
    from matplotlib.ticker import MultipleLocator
    import datetime
    
    # Generate some data
    d = datetime.timedelta(hours=1/5)
    now =  datetime.datetime.now()
    times = [now + d * j for j in range(250)]
    
    ax = plt.gca() # get the current axes
    ax.plot(times, range(len(times)))
    
    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(30)
    
    # Set the positions of the major and minor ticks
    dayLocator = MultipleLocator(1)
    hourLocator = MultipleLocator(1/24)
    ax.xaxis.set_major_locator(dayLocator)
    ax.xaxis.set_minor_locator(hourLocator)
    
    # Convert the labels to the Y-m-d format
    xax = ax.get_xaxis() # get the x-axis
    adf = xax.get_major_formatter() # the the auto-formatter
    adf.scaled[1/24] = '%Y-%m-%d'  # set the < 1d scale to Y-m-d
    adf.scaled[1.0] = '%Y-%m-%d' # set the > 1d < 1m scale to Y-m-d
    
    plt.show()
    

    后果

    enter image description here