如何每小时获得一次?

时间:2018-02-14 15:10:49

标签: python pandas matplotlib

考虑这个简单的例子

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates

pd.__version__
Out[147]: u'0.22.0'

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')

df = pd.Series(np.random.randn(len(idx)),  index = idx)
df.head()
Out[145]: 
2017-01-01 05:03:00   0.4361
2017-01-01 05:04:00   0.9737
2017-01-01 05:05:00   0.8430
2017-01-01 05:06:00   0.4292
2017-01-01 05:07:00   0.5739
Freq: T, dtype: float64

我想绘制这个,并且每小时都有一个滴答声。我用:

fig, ax = plt.subplots()
hours = mdates.HourLocator(interval = 1)  #
h_fmt = mdates.DateFormatter('%H:%M:%S')

df.plot(ax = ax, color = 'black', linewidth = 0.4)

ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

给出了

enter image description here

为什么这里每小时都不会出现蜱?谢谢你的帮助!

2 个答案:

答案 0 :(得分:16)

问题在于,虽然pandas通常直接包装matplotlib绘图方法,但对于具有日期的绘图则不是这种情况。一旦涉及日期,大熊猫使用完全不同的日期数字表示,因此也使用自己的定位器作为标记。

如果您想在使用pandas创建的图表上使用matplotlib.dates格式化程序或定位器,您可以在pandas图中使用x_compat=True选项。

df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)

这允许使用matplotlib.dates格式器或定位器,如下所示。 否则,您可以用

替换df.plot(ax = ax, color = 'black', linewidth = 0.4)
ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)

完整示例:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')
df = pd.Series(np.random.randn(len(idx)),  index = idx)

fig, ax = plt.subplots()
hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M:%S')

ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)
#or use
df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)
#Then tick and format with matplotlib:
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

fig.autofmt_xdate()
plt.show()

enter image description here

<小时/> 如果在这里使用大熊猫的动机是(如下面的评论中所述)能够使用secondary_y,则matplotlib图的等效项将是双轴twinx

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')

df = pd.DataFrame(np.cumsum(np.random.randn(len(idx), 2),0), 
                  index = idx, columns=list("AB"))

fig, ax = plt.subplots()
ax.plot(df.index, df["A"], color = 'black')
ax2 = ax.twinx()
ax2.plot(df.index, df["B"], color = 'indigo')

hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)

fig.autofmt_xdate()
plt.show()

enter image description here

答案 1 :(得分:1)

仅使用熊猫的解决方案

您可以使用 DatetimeIndex 的时间戳设置每小时的刻度。可以利用时间戳的 datetime properties 创建刻度。

import numpy as np   # v 1.19.2
import pandas as pd  # v 1.1.3

idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq='min')
series = pd.Series(np.random.randn(len(idx)), index=idx)

ax = series.plot(color='black', linewidth=0.4, figsize=(10,4))
ticks = series.index[series.index.minute == 0]
ax.set_xticks(ticks)
ax.set_xticklabels(ticks.strftime('%H:%M'));

hour_ticks