【问题标题】:How do I plot timeseries data in Python?如何在 Python 中绘制时间序列数据?
【发布时间】:2021-11-05 01:24:13
【问题描述】:

我处理大量时间序列数据,并希望有一种方法可以简单地按季节进行绘制;

例如;

            A  B  C  D  E  F  G H I
01/01/2008  4  4  43 4  3 4  3  4 3
02/01/2008  43 3  4  3  34  3  4  3
03/01/2008 11 2  3 4  3  4  3 44 3 
.
.
.
07/08/2021 43 3  4  3  34  3  4  3
08/09/2021 43 3  4  3  34  3  4  3

是否有一种有效的或 python-y 的方式来绘制它,使其类似于季节性图表,但按每日粒度?

可能类似于以下内容?

理想情况下,这也可以创建一个数据框,其中包含年度数据列,索引为 dd/mm 日期格式。

非常感谢任何帮助!

【问题讨论】:

    标签: python pandas time-series resampling


    【解决方案1】:

    请注意,监控时间序列数据的季节性不同于绘制时间序列数据。随着时间的推移,需要将数据分解为其组件。你可以检查这个answer。然而,只是为了绘制时间序列数据而不管format of timestamps在黑暗背景下使用plt.style.use('dark_background'),它可能如下:

    import pandas as pd
    import matplotlib.pyplot as plt
    plt.style.use('dark_background')
    
    colors = [
        '#08F7FE',  # teal/cyan
        '#FE53BB',  # pink
        '#F5D300',  # yellow
        '#00ff41'  # matrix green
                 ]
    
    df = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1],
                       'B': [4, 5, 5, 7, 9, 8, 6],
                       'C': [7, 5, 3, 1, 5, 9, 3],
                       'D': [3, 6, 7, 4, 3, 2, 1],
                      'date':['10-10-2016', '10-10-2017', '10-10-2018', '10-10-2019', '10-10-2020', '10-10-2021', '10-10-2022']})
    
    # make sure the time column is actually time format
    df['date']=pd.to_datetime(df['date'])
    
    # set time as the index
    df.set_index('date',inplace=True)
    
    fig, ax = plt.subplots()
    
    df.plot(marker='o', color=colors, ax=ax)
    
    ax.figure.autofmt_xdate(rotation=45, ha='center')
    plt.legend(loc='best')
    plt.show()
    

    如果你想让它更花哨,你可以关注Time series VisualizationMatplotlib Cyberpunk Style

    为了解决以下问题:

    理想情况下,这也可以创建一个数据框,其中包含年度数据列,索引为 dd/mm 日期格式。

    基于此post,一旦将日期索引传递给 x 轴,您就可以使用具有所需日期格式的 import matplotlib.dates as md

    df.plot(marker='o', color=colors, ax=ax)
    ax.set_xticks(df.index)
    ax.figure.autofmt_xdate(rotation=45, ha='center')
    
    ####### Use the below functions #######
    import matplotlib.dates as md
    dtFmt = md.DateFormatter('%d-%b') # define the formatting
    ax.xaxis.set_major_formatter(dtFmt) # apply the format to the desired axis
    
    plt.legend(loc='best')
    plt.show()
    

    【讨论】:

      【解决方案2】:
      • 情节简单
      • 已经用随机数据模拟了您的数据
      • 关键步骤是一个 x 轴,它在不同年份保持季节性不变。已使用 2021 年的日期生成 2021 年的日期。第二步是设置日期格式,因为年份无关紧要
      • 我的数据显然没有季节性,因为它是随机的...
      import numpy as np
      import pandas as pd
      import plotly.express as px
      
      n = 365 * 14
      df = pd.DataFrame(
          index=pd.date_range("1-jan-2008", periods=n),
          data={c: np.random.randint(1, 45, n) for c in list("ABCDEFGHI")},
      )
      
      fig = px.line(
          df.assign(
              year=df.index.year,
              doy=pd.to_datetime(df.index.day_of_year.values + (2021 * 1000), format="%Y%j"),
              value=df.mean(axis=1),
          ),
          x="doy",
          y="value",
          color="year",
          template="plotly_dark"
      )
      
      # just for demo purposes, make some traces invisible
      for t in fig.data:
          if int(t["name"])<2016: t["visible"]="legendonly"
      
      fig.update_layout(xaxis={"tickformat":"%d-%b"})
      
      
      

      【讨论】:

      • 你能更新这个答案吗?无法复制!为什么我们需要在这个可视化中doy
      • @Mario 为我工作 pandas 1.3.4 plotly 5.5.0 在 jupyter 环境中运行。使用 doy 是因为它在 xaxis 多年来保持一致。
      • 我刚刚在 google colab notebook 中仔细检查了默认版本 pandas==1.1.5plotly==4.4.1Python 3.7.12 由于AttributeError: 'DatetimeIndex' object has no attribute 'day_of_year' 而仍然存在问题,但是对于您提到的那些软件包版本工作。
      【解决方案3】:

      对于绘图,我建议你看看 matplotlib。对于数据框,您可以使用 pandas

      import matplotlib.pyplot as plt
      import pandas as pd
      df = pd.DataFrame(yourdata) #to create a dataframe
      df.plot() #to plot your data or df.plot(x="A",y="Date") to select what to plot
      df["NewDate"] = pd.to_datetime(df['Date'], format='%d/%m') #to create the the date column with format dd/mm (based on the date column you already have)
      

      【讨论】:

      • 这仍然只是将数据绘制为一条线,而不是每年一条线,以显示我担心的季节性。
      • 你是对的,请原谅我的英语不好,我没听懂这个问题:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2020-05-23
      • 2020-04-09
      • 2018-10-21
      相关资源
      最近更新 更多