gpt4 book ai didi

python - Pandas plotting--忽略时间范围

转载 作者:行者123 更新时间:2023-11-28 19:00:27 25 4
gpt4 key购买 nike

假设我在三天的上午 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 点的好方法?

最佳答案

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

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

关于python - Pandas plotting--忽略时间范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53267385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com