【发布时间】:2021-04-29 09:34:21
【问题描述】:
问题概述
我正在尝试为我运行的实验绘制一个采样时间表。我们开始每 3 小时采样一次,我希望能够观察每个样本在每日周期中绘制的时间。
- x 轴变量应该是一天中的时间 (00:00 - 23:00)。
- 每一行(或者可能是 y 轴变量?)都应该是新的一天。
- 与理想的 3 小时采样策略相比,该点应根据是早期发布(蓝色)还是延迟发布(红色)来着色。
我设想的情节如下所示:
模拟虚拟数据来解释问题
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas.tseries.offsets import DateOffset
import matplotlib.dates as mdates
import itertools
value = np.random.normal(size=100)
expected_time = pd.date_range("2000-01-01", freq="180min", periods=100)
# add random offset to simulate being +/- the true expected release time
time_deltas = np.array([DateOffset(minute=max(0, min(int(i), 59))) for i in np.abs(np.random.normal(0, 10, size=100))])
time = [expected_time[i] + time_deltas[i] if (i % 2 == 0) else expected_time[i] - time_deltas[i] for i in range(100)]
df = pd.DataFrame({"launchtime": time, "value": value})
ds = df.set_index("launchtime").to_xarray()
ds = ds.assign_coords(expected_time=("launchtime", expected_time))
如您所见,基础数据大约每 3 小时有一次观察(尽管确切时间略有不同)。
In []: ds["launchtime.hour"]
Out[]:
<xarray.DataArray 'hour' (launchtime: 100)>
array([ 0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21, 0,
3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21, 0, 3,
6, 9, 12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6,
9, 12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9,
12, 15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9, 12,
15, 18, 21, 0, 3, 6, 9, 12, 15, 18, 21, 0, 3, 6, 9])
Coordinates:
* launchtime (launchtime) datetime64[ns] 2000-01-01 ... 2000-01-13T09:0...
expected_time (launchtime) datetime64[ns] 2000-01-01 ... 2000-01-13T09:0...
使用matplotlib 的初始尝试
# get the total number of days
day_months = list(itertools.product(np.unique(ds["launchtime.day"].values), np.unique(ds["launchtime.month"].values)))
N_DAYS = len(day_months)
fig, axs = plt.subplots(N_DAYS, 1, figsize=(6, 0.5*N_DAYS), sharey=True)
for ix, (day, month) in enumerate(day_months):
mask = (ds["launchtime.day"] == day) & (ds["launchtime.month"] == month)
day = ds.sel(launchtime=mask)
error = np.array([pd.to_datetime(dt) for dt in day.launchtime.values]) - np.array([pd.to_datetime(dt) for dt in day.expected_time.values])
error = [e.total_seconds() for e in error]
colors = ["r" if e > 0 else "b" if e < 0 else "grey" for e in error]
print(colors)
ax = axs[ix]
ax.scatter(day.expected_time, [1 for _ in range(len(day.expected_time))], color=colors)
ax.set_ylabel(f"Day {ix}")
# remove the spines and ytick labels
for spine in ax.spines:
ax.spines[spine].set_visible(False)
ax.axes.yaxis.set_visible(False)
plt.xticks(rotation=60)
fig.suptitle("Radiosonde Releases over a month campaign")
# 剩余问题
我看到的主要问题是:
- x 轴应该是每日周期,而不是还包括日/月/年的“日期时间”
- 将每一天整齐地堆叠为一个新列会很好,可以作为一个方面,也可以将每一天用作 y 轴变量
【问题讨论】:
标签: python python-3.x pandas matplotlib