熊猫绘图-忽略时间范围

时间:2018-11-12 17:39:54

标签: python pandas matplotlib

假设我在三天的上午8点至下午4点的工作时间内拥有一分钟的数据。我想使用pandas图函数来绘制这些数据:

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

np.random.seed(51723)
dates = pd.date_range("11/8/2018", "11/11/2018", freq = "min")
df = pd.DataFrame(np.random.rand(len(dates)), index = dates, columns = ['A'])
df = df[(df.index.hour >= 8) & (df.index.hour <= 16)]  # filter for business hours

fig, ax = plt.subplots()
df.plot(ax = ax)
plt.show()

但是,plot函数还包括绘图中的过夜时间,导致在此期间意外绘图:

bad plotting

我将连续绘制数据,而忽略了隔夜时间(类似这样): good plotting

仅绘制预期的上午8点至下午4点的时间的好方法是什么?

1 个答案:

答案 0 :(得分:0)

这可以通过在不同的轴上绘制每个日期来完成。但是在某些情况下,诸如标签之类的东西会变得局促。

import datetime
import matplotlib.pyplot as plt

pdates = np.unique(df.index.date)  # Unique Dates 

fig, ax = plt.subplots(ncols=len(pdates), sharey=True, figsize=(18,6))

# Adjust spacing between suplots 
# (Set to 0 for continuous, though labels will overlap)
plt.subplots_adjust(wspace=0.05)

# Plot all data on each subplot, adjust the limits of each accordingly
for i in range(len(pdates)):
    df.plot(ax=ax[i], legend=None)
    # Hours 8-16 each day:
    ax[i].set_xlim(datetime.datetime.combine(pdates[i], datetime.time(8)), 
                   datetime.datetime.combine(pdates[i], datetime.time(16)))

    # Deal with spines for each panel
    if i !=0:
        ax[i].spines['left'].set_visible(False)
        ax[i].tick_params(right=False,
                  which='both',
                  left=False,
                  axis='y')
    if i != len(pdates)-1:
        ax[i].spines['right'].set_visible(False)
plt.show()

enter image description here