【问题标题】:divide x and y labels in Matplotlib在 Matplotlib 中划分 x 和 y 标签
【发布时间】:2018-08-01 07:49:49
【问题描述】:

我有一个图表,其中 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()

【问题讨论】:

    标签: python python-3.x matplotlib graph


    【解决方案1】:

    您可以将matplotlib.ticker 中的MultipleLocatorset_major_locatorset_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()
    

    结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-07
      • 2012-03-14
      • 2023-04-04
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 2019-12-18
      • 2022-01-11
      相关资源
      最近更新 更多