【问题标题】:How to plot dates on the x-axis using Seaborn (or matplotlib)如何使用 Seaborn(或 matplotlib)在 x 轴上绘制日期
【发布时间】:2016-08-30 12:55:45
【问题描述】:

我有一个包含一些时间序列数据的 csv 文件。我这样创建一个数据框:

df = pd.read_csv('C:\\Desktop\\Scripts\\TimeSeries.log')

当我调用df.head(6)时,数据显示如下:

Company     Date                 Value
ABC         08/21/16 00:00:00    500
ABC         08/22/16 00:00:00    600
ABC         08/23/16 00:00:00    650
ABC         08/24/16 00:00:00    625
ABC         08/25/16 00:00:00    675
ABC         08/26/16 00:00:00    680

然后,我有以下内容将“日期”列强制为日期时间格式:

df['Date'] = pd.to_datetime(df['Date'], errors = 'coerce')

有趣的是,当我调用以下命令时,我看到了“pandas.core.series.Series”:

type(df['Date'])

最后,我调用以下命令来创建情节:

%matplotlib qt
sns.tsplot(df['Value'])

在从左到右的 x 轴上,我看到整数范围从 0 到数据框中的行数。如何将“日期”列作为 x 轴值添加到该图中?

谢谢!

【问题讨论】:

  • 尝试使用df.set_index (...)将“日期”列设置为索引
  • 或将df 作为第一个参数,然后相应地指定time 和value kwargs。

标签: python matplotlib seaborn timeserieschart


【解决方案1】:

不确定 tsplot 是不是最好的工具。您可以使用:

df[['Date','Value']].set_index('Date').plot()

【讨论】:

  • 这很简单且有效,但可能需要注意的是,如果数据中不存在所有连续日期,则不会生成与时间流逝连续/线性的轴。
  • 可以使用resample() 获得连续轴。
【解决方案2】:

我认为为时已晚。

首先,您必须注意“日期”列是一系列“日期时间”类型,因此您应该这样做以获得“日期”部分:

df['Date'] = df['Date'].map(lambda x:x.date())

现在按“日期”对数据框进行分组,然后重置索引以使“日期”成为一列(而不是索引)。

那么你可以使用plt.plot_date

df_groupedby_date = df.groupby('Date').count()
df_groupedby_date.reset_index(inplace=True)
plt.plot_date(x=df_groupedby_date['Date'], y=df_groupedby_date['Value'])

【讨论】:

    【解决方案3】:

    将time 参数用于tsplot

    来自文档:

    time : string or series-like
        Either the name of the field corresponding to time in the data DataFrame or x values for a plot when data is an array. If a Series, the name will be used to label the x axis.
    #Plot the Value column against Date column
    sns.tsplot(data = df['Value'], time = df['Date'])
    

    但是,tsplot 用于在同一时间窗口中针对不同条件绘制时间序列。要绘制单个时间序列,您还可以使用 plt.plot(time = df['Date'], data = df['Value'])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-26
      • 2017-12-30
      • 2020-06-09
      • 2018-08-31
      相关资源
      最近更新 更多