【问题标题】:Plotting pandas Series line becomes curved绘制熊猫系列线变得弯曲
【发布时间】:2017-09-20 11:25:30
【问题描述】:

问题是绘制一条日期分布不均匀的直线。使用系列值数据可以解决曲线问题,但会丢失时间线(日期)。有没有办法解决这个问题?

编辑:为什么日期不直接映射到 x 轴上的刻度:

0 -> 2017-02-17,
1 -> 2017-02-20,
... ?

现在橙色线似乎有 12 个刻度,但只有 8 个数据点。

import pandas as pd
import matplotlib.pyplot as plt

def straight_line(index):  
  y = [3 + 2*x for x in range(len(index))] 
  zserie = pd.Series(y, index=index)

  return zserie

if __name__ == '__main__':

  start = '2017-02-10'
  end = '2017-02-17'
  index = pd.date_range(start,end)

  index1 = pd.DatetimeIndex(['2017-02-17', '2017-02-20', '2017-02-21', '2017-02-22',
               '2017-02-23', '2017-02-24', '2017-02-27', '2017-02-28',],
              dtype='datetime64[ns]', name='pvm', freq=None)   

  plt.figure(1, figsize=(8, 4))  

  zs = straight_line(index)
  zs.plot()

  zs = straight_line(index1)
  zs.plot()

  plt.figure(2, figsize=(8, 4))  

  zs = straight_line(index1) 
  plt.plot(zs.values)

【问题讨论】:

  • 您是要创建一条日期间距不均匀的直线(x 轴),还是要让日期值表现得像一个分类值?
  • 第一个情节中的橙色线似乎正是您正在寻找的情节。它有什么问题?
  • 要获得一条直线,您必须以与 y 轴相同的速率调整 x 轴。这实际上不适用于针对彼此不同距离的日期进行绘图。为什么数据需要图表在一条直线上?
  • 哦,我应该解释一下,最初的问题是将带有回归线的时间序列绘制成带有日期的同一图形的常见任务。回归线应该是直的。
  • 为什么日期不直接映射到数据点,例如:

标签: python pandas matplotlib plot time-series


【解决方案1】:

图表正确地将日期视为连续变量。 index_1 的日子应该绘制在 x 坐标 17、20、21、22、23、24、27 和 28 处。所以,带有橙色线的图形是正确的。 p>

问题在于您在 straight_line() 函数中计算 y 值的方式。您将日期视为只是分类值并忽略日期之间的间隔。线性回归计算不会这样做——它将日期视为连续值。

要在示例代码中获得一条直线,您应该使用td = (index - index[0])(返回熊猫TimedeltaIndex)将index_1 中的值从绝对日期转换为相对差异,然后使用td 中的日期用于计算的 x 值。我已经在下面的 reg_line() 函数中展示了如何做到这一点:

import pandas as pd
import matplotlib.pyplot as plt

def reg_line(index):
    td = (index - index[0]).days  #array containing the number of days since the first day
    y = 3 + 2*td
    zserie = pd.Series(y, index=index)
    return zserie

if __name__ == '__main__':

  start = '2017-02-10'
  end = '2017-02-17'
  index = pd.date_range(start,end)

  index1 = pd.DatetimeIndex(['2017-02-17', '2017-02-20', '2017-02-21', '2017-02-22',
               '2017-02-23', '2017-02-24', '2017-02-27', '2017-02-28',],
              dtype='datetime64[ns]', name='pvm', freq=None)   

  plt.figure(1, figsize=(8, 4))  

  zs = reg_line(index)
  zs.plot(style=['o-'])

  zs = reg_line(index1)
  zs.plot(style=['o-'])

生成下图:

注意:我在图表中添加了点,以明确在图表上绘制了哪些值。如您所见,橙色线是直的,即使该范围内的某些日期没有值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2013-11-25
    • 2016-06-23
    • 1970-01-01
    • 2018-12-11
    相关资源
    最近更新 更多