【问题标题】:Multiple timeseries plots from Pandas Dataframe来自 Pandas Dataframe 的多个时间序列图
【发布时间】:2016-07-08 19:11:31
【问题描述】:

我正在尝试使用 pandas 编写我的第一个 python 脚本。我有 10 年的风数据(1 分钟读数),我需要创建月度图,并在每个图上绘制速度和方向。

输入的 csv 数据如下所示:

Date,Speed,Dir,
2014-01-01 00:00:00, 13, 179,
2014-01-01 00:01:00, 13, 178,
2014-01-01 00:02:00, 11, 169,
2014-01-01 00:03:00, 11, 178,
2014-01-01 00:04:00, 11, 181,

到目前为止,我已经编写了以下内容,这将为日期范围内设置的月份创建一个图。除了我需要修复 x 轴标签外,我通常对这个图的外观感到满意。

我想遍历整个数据集并为每个月创建一个 pdf 图。如有任何帮助,我们将不胜感激!

import glob, os
import pandas as pd
from pandas import Series, DataFrame, Panel
import numpy as np
import matplotlib.pyplot as plt

wind = pd.read_csv('2014.csv')

wind['Date']=pd.to_datetime(wind['Date'])
wind=wind.set_index('Date')

dates = pd.date_range('2014-01', '2014-2', freq='1min')

janwin = Series(wind['Speed'], index=dates)
jandir = Series(wind['Dir'], index=dates)

plt.figure(1)
plt.subplot(211)
plt.plot(dates, janwin)

plt.ylabel("Km/hr")
plt.rcParams.update({'font.size': 4})
plt.grid(which='major', alpha = .5)


plt.subplot(212)
plt.plot(dates, jandir)
plt.ylabel("Degrees")
plt.rcParams.update({'font.size': 4})
plt.grid(which='major', alpha = 5)
plt.ylim(0,360)
plt.axis(minor=True) 

plt.savefig('test.pdf', dpi=900)

Sample Plot

【问题讨论】:

    标签: python pandas matplotlib plot


    【解决方案1】:

    非常感谢 flymeatball 向我展示了如何遍历数据。通过我的第一个脚本,我学到了很多东西,希望它对其他人有用的参考。

    下面的代码读入一个包含 1 分钟平均风向和风向数据的 csv,并带有一个日期/时间字段,并绘制了一个包含每个月速度和方向时间序列的图形。

    编辑:自发布此消息以来,我注意到以下将数据绘制到该月最后一天的第一个时间戳(缺少约 24 小时的数据)。这是因为 CurrMoEnd 只返回一个日期。

    #Plots monthly wind speed data from 1min average recordings to PDF
    import pandas as pd
    import matplotlib.pyplot as plt
    import datetime
    from dateutil.relativedelta import relativedelta
    import calendar
    
    
    data = pd.read_csv('data.csv')
    
    data['Date']=pd.to_datetime(data['Date'])
    
    rawDf = pd.DataFrame(data, columns = ['Date','Speed','Dir'])
    
    
    #Define beginning and end of loop - start at first month, end at last month
    currDate = datetime.date(rawDf['Date'].min().year, rawDf['Date'].min().month, 1)
    endDate = datetime.date(rawDf['Date'].max().year, rawDf['Date'].max().month, 1)
    
    
    #loop through and plot each month of data
    while currDate <= endDate:
    
    currMoEnd = datetime.date(currDate.year, currDate.month, calendar.monthrange(currDate.year,currDate.month)[1])
    wind = rawDf[(rawDf['Date']>= currDate) & (rawDf['Date']<= currMoEnd)]
    wind.set_index('Date', inplace = True)
    
    dates = pd.date_range(currDate, currMoEnd, freq='1min')
    
    win = pd.Series(wind['Speed'], index=dates)
    dirc = pd.Series(wind['Dir'], index=dates)
    
    #Set figure size roughly to A4 paper size
    plt.figure(1, figsize = (11.3, 8))
    
    plt.subplot(211)
    plt.plot(dates, win, lw = 0.15)
    plt.ylabel("Km/hr")
    plt.rcParams.update({'font.size': 4})
    plt.grid(which='major')
    
    
    plt.subplot(212)
    plt.plot(dates, dirc, lw = 0.15)
    plt.ylabel("Degrees")
    plt.rcParams.update({'font.size': 4})
    plt.grid(which='major')
    plt.yticks([0, 45, 90, 135, 180, 225, 270, 315, 360])
    plt.ylim(0,360)
    plt.axis(minor=True) 
    
    #convert current month to for file name
    month = int(currDate.strftime('%m'))
    year= int(currDate.strftime('%Y'))
    
    #Plot PDF to current directory/year/month output.pdf
    plt.savefig("{}/{} Output.pdf".format(year, month), dpi = 900)
    plt.show()
    
    #increment current date    
    currDate = currDate + relativedelta(months = 1)
    

    【讨论】:

      【解决方案2】:

      欢迎来到 Stackoverflow。通常,当您在此类问题上寻求帮助时,最好一直工作到遇到特定实例/问题,然后再寻求帮助。很难告诉你如何做这么广泛的事情,而且通常你不会得到很好的回应,因为看起来你只是懒惰并寻求帮助,而不是一直尝试解决问题。我看到您需要解决许多问题,但从广义上讲,您需要设置一个循环并弄清楚如何启动/停止循环,以及如何仅绘制您当前感兴趣的月份的数据。

      以下是我从内存中快速编写的一些示例代码(尚未运行),我确信有更好的方法可以做到这一点,但希望它能让你走上正轨。将来,如果您可以将帖子提炼到基本部分,您将获得最佳回复。在这种情况下,每天两个月的样本数据框将有助于进行迭代/绘图。然后,您可以获取工作代码并调整到分钟。

      如果这有帮助,请点赞并努力确保此处列出的最终代码对关注您的人有用。

      import pandas as pd
      import matplotlib.pyplot as plt
      import datetime
      from dateutil.relativedelta import relativedelta
      import calendar
      
      #wind = pd.read_csv('2014.csv')
      data = [['2014-01-01 00:00:00', 13, 179],
              ['2014-01-01 00:01:00', 13, 178],['2014-01-01 00:02:00', 11, 169],['2014-01-01 00:03:00', 11, 178], 
              ['2014-01-01 00:04:00', 11, 181]]
      
      rawDf = pd.DataFrame(data, columns = ['Date','Speed','Dir'])
      
      rawDf['Date']=pd.to_datetime(rawDf['Date'])
      
      #Define beginning and end of loop - start at first month, end at last month
      currDate = datetime.date(rawDf['Date'].min().year, rawDf['Date'].min().month, 1)
      endDate = datetime.date(rawDf['Date'].max().year, rawDf['Date'].max().month, 1)
      
      
      #loop
      while currDate <= endDate:
      
          currMoEnd = datetime.date(currDate.year, currDate.month, calendar.monthrange(currDate.year,currDate.month)[1])
          wind = rawDf[(rawDf['Date']>= currDate) & (rawDf['Date']<= currMoEnd)]
          wind.set_index('Date', inplace = True)
      
          dates = pd.date_range(currDate, currMoEnd, freq='1min')
      
          janwin = pd.Series(wind['Speed'], index=dates)
          jandir = pd.Series(wind['Dir'], index=dates)
      
          plt.figure(1)
          plt.subplot(211)
          plt.plot(dates, janwin)
      
          plt.ylabel("Km/hr")
          plt.rcParams.update({'font.size': 4})
          plt.grid(which='major', alpha = .5)
      
      
          plt.subplot(212)
          plt.plot(dates, jandir)
          plt.ylabel("Degrees")
          plt.rcParams.update({'font.size': 4})
          plt.grid(which='major', alpha = 5)
          plt.ylim(0,360)
          plt.axis(minor=True) 
      
          plt.show()
          plt.savefig('{0}_output.pdf'.format(datetime.stftime(currDate,'%Y-%m')),  dpi=900)
      
          currDate = currDate + relativedelta(months = 1)
      

      【讨论】:

      • 喜点 :) 我应该更清楚一点,我不确定如何循环几个月,并且在获得有关如何这样做的建议之后。这是一个很大的帮助,一旦我有一个示例供其他人遵循,我将更新该帖子。谢谢大家!
      猜你喜欢
      • 1970-01-01
      • 2016-11-06
      • 2022-12-05
      • 1970-01-01
      • 2012-08-20
      • 2016-08-25
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      相关资源
      最近更新 更多