【问题标题】:format graph of data using Pandas datetime index使用 Pandas 日期时间索引格式化数据图
【发布时间】:2020-05-17 14:50:41
【问题描述】:

我想绘制一个名为 vslr 的 pandas 数据框(414 行,2 列,但我得到的图表无法使用。

我用来绘图的命令:

plt.plot(vslr['Price'],vslr['Date'])

图表:

我的数据:

print(vslr.head)
                 Date   Price
0    2020-01-31 15:30:00  8.1653
1    2020-01-31 14:30:00  8.2087
2    2020-01-31 13:30:00  8.1753
3    2020-01-31 12:30:00  8.1551
4    2020-01-31 11:30:00  8.0903
..                   ...     ...
409  2019-11-05 13:30:00  6.8452
410  2019-11-05 12:30:00  6.8050
411  2019-11-05 11:30:00  6.7600
412  2019-11-05 10:30:00  6.7553
413  2019-11-05 09:30:00  6.6502

vslr.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 414 entries, 0 to 413
Data columns (total 2 columns):
Date     414 non-null object
Price    414 non-null object
dtypes: object(2)
memory usage: 6.6+ KB

感谢您的帮助:)

【问题讨论】:

    标签: python pandas datetime plot graph


    【解决方案1】:

    IIUC,你得到一个“无用”的图表,因为你选择在轴上绘制日期,通常你会在x-axis 上绘制日期,在y-axis 上绘制价格,然后检查你的图表。 在Matplotlib.plot() 中,第一个参数绘制在 x 轴上,第二个参数绘制在 y 轴上

    您可能需要按日期以及按升序对数据框进行排序以供此使用:

    vslr.sort_values(by='Date', ascending=True, inplace=True)
    plt.plot(vslr['Date'],vslr['Price'])
    

    注意,由于这是一个DateTime 时间列,缺失的日期也会得到它们的刻度。 您的主要目标似乎是绘制价格与日期,以便您也可以从 Date 列中提取它们。

    vslr['Date']=pd.to_datetime(vslr['Date'])
    vslr['Date']=vslr['date'].dt.date
    

    如果您将索引设置为datetime,matplotlib 将为您处理 x 轴。这里是一个例子

    import pandas as pd
    import matplotlib.pyplot as plt
    
    date_time = ["2011-09-01", "2011-08-01", "2011-07-01", "2011-06-01", "2011-05-01"]
    date_time = pd.to_datetime(date_time)
    temp = [2, 4, 6, 4, 6]
    
    DF = pd.DataFrame()
    DF['temp'] = temp
    DF = DF.set_index(date_time)
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.3)
    plt.xticks(rotation=90)
    plt.plot(DF)
    

    df 索引设置为datetime 系列允许matplotlib 处理时间序列数据上的x-axis,还可以查看此link 以处理x 轴上的间距。

    【讨论】:

      【解决方案2】:

      据我观察,您正在处理时间序列数据,如果您只想在不进行一些预处理的情况下绘制它(将其划分为几个月可能是每年一次),请关注这篇文章here

      但是让我们假设您希望将数据集划分为可以使用日期 properties 执行以下操作的段,然后将其绘制在该轴上。

       vslr['date']=pd.to_datetime(vslr['date'])
       vslr['month']=vslr['date'].dt.month
       vslr.groupby('month').aggregate({'Price':'sum'}).reset_index()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-07
        • 2019-02-15
        • 2017-07-11
        • 2018-11-12
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 2020-10-09
        相关资源
        最近更新 更多