【问题标题】:Plot 15 minute interval data with days and months as the x axis ticks绘制 15 分钟间隔数据,其中 x 轴刻度为天和月
【发布时间】:2017-07-10 19:05:14
【问题描述】:

我每隔 15 分钟记录一次数据。我想绘制这些数据并让 x 轴每天显示一个小刻度,每个月显示一个主要刻度。这是我在 1 月和 2 月尝试做的事情的 sn-p。

#!/usr/bin/env python3
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

#make some data
t = np.arange(0, 5664, 1) # Jan and Feb worth of 15 minute steps
s = np.sin(2*np.pi*t) # data measured

#plot the data
fig, ax = plt.subplots()
ax.plot(t, s)

#select formatting
days = mdates.DayLocator()
daysfmt = mdates.DateFormatter('%d')
months = mdates.MonthLocator()
monthsfmt = mdates.DateFormatter('\n%b')

从我阅读并试图在脑海中拼凑起来的文档和其他问答中,我知道我需要告诉 matplotlib 我想用于 x 轴的格式。这是我感到困惑的地方。我不知道如何表明绘图数据是每 15 分钟一次(每个次要刻度 1440 个样本),因此当我显示绘图时,图表上没有显示任何内容。或者至少我认为这是原因......

#apply formatting
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsfmt)
ax.xaxis.set_minor_locator(days)
ax.xaxis.set_minor_formatter(daysfmt)

#select dates
datemin = dt.datetime.strptime('01/01/17', '%d/%m/%y')
datemax = dt.datetime.strptime('28/02/17', '%d/%m/%y')
ax.set_xlim(datemin, datemax)

plt.show()

绘制结果

【问题讨论】:

    标签: python datetime matplotlib


    【解决方案1】:

    在那里,工作;)

    您的代码有两个问题:

    1. 您正在绘制 t 和 s,但将 x 轴设置为错误的比例

    2. 您只是在绘制 sin(x) 的数值噪声,因为您总是使用 2pi 的倍数作为 sin 的参数,并且对于任何整数 n,sin(n*2pi) = 0

    完整代码:

    #!/usr/bin/env python3
    import num
    
    py as np
    import datetime as dt
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    
    
    
    #make some data
    t = np.arange(0, 5664, 0.1) # Jan and Feb worth of 15 minute steps
    s = np.sin(2*np.pi*t) # data measured
    
    #plot the data
    fig, ax = plt.subplots()
    #ax.plot(t, s)
    
    #select formatting
    days = mdates.DayLocator()
    daysfmt = mdates.DateFormatter('%d')
    months = mdates.MonthLocator()
    monthsfmt = mdates.DateFormatter('\n%b')
    
    #apply formatting
    ax.xaxis.set_major_locator(months)
    ax.xaxis.set_major_formatter(monthsfmt)
    ax.xaxis.set_minor_locator(days)
    ax.xaxis.set_minor_formatter(daysfmt)
    
    #select dates
    datemin = dt.datetime.strptime('01/01/17', '%d/%m/%y')
    datemax = dt.datetime.strptime('28/02/17', '%d/%m/%y')
    
    
    t0 = dt.datetime(2017,1,1)
    t_datetime = [ t0 + dt.timedelta(minutes=15*t_) for t_ in t ]
    
    ax.plot(t_datetime,s)
    
    ax.set_xlim(t0, t_datetime[-1])
    
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 2020-11-04
      • 1970-01-01
      相关资源
      最近更新 更多