-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_gravity_from_excel.py
More file actions
198 lines (161 loc) · 7.14 KB
/
plot_gravity_from_excel.py
File metadata and controls
198 lines (161 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# GRAVITY — 날짜별 개별 창 + (날짜/데이터 조건별) 동시간 펼치기 + 체크박스 고정 + 시간축(밀리초 2자리)
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
import matplotlib.dates as mdates
from matplotlib.ticker import FuncFormatter
EXCEL_PATH = r"손목돌리기.xlsx"
SHEET_NAME = "sensor_data_f_g"
TIME_COL = "measured_at"
X_COL = "x"
Y_COL = "y"
Z_COL = "z"
SHOW_MAGNITUDE = False
SMOOTH_WINDOW = 0
SAVE_PNG_DIR = None # 예: r"./out_gravity"
def build_plot_time_by_timestamp(df: pd.DataFrame, time_col: str,
fallback: str = 'median',
jitter_us: int = 1000) -> pd.Series:
"""
같은 timestamp 블록을 T..T_next 사이에 인덱스 비율(frac)대로 균등 분할해 배치.
(주의) 하루 단위 데이터에 적용 권장
"""
t = pd.to_datetime(df[time_col])
uniq = t.drop_duplicates(keep='first').reset_index(drop=True)
next_map = pd.Series(uniq.shift(-1).values, index=uniq.values) # {T: T_next}
t_next = t.map(next_map)
med_dt = t.sort_values().diff().median()
if pd.isna(med_dt) or med_dt == pd.Timedelta(0):
med_dt = pd.Timedelta(seconds=1)
grp = df.groupby(time_col, sort=False, dropna=False)
rank = grp.cumcount()
size = grp[time_col].transform('size')
frac = (rank + 1) / (size + 1)
dt = (t_next - t)
dt = dt.where(dt > pd.Timedelta(0), pd.NaT)
if fallback == 'median':
dt = dt.fillna(med_dt)
else:
dt = dt.fillna(pd.Timedelta(microseconds=jitter_us))
offset = dt * frac
return (t + offset).astype('datetime64[ns]')
def moving_average(s: pd.Series, window: int) -> pd.Series:
if window and window > 1:
return s.rolling(window, min_periods=max(1, window//2)).mean()
return s
def setup_time_of_day_axis(ax, tseries: pd.Series):
"""시:분:초(.ms 2자리) 포맷으로 표시"""
tseries = pd.to_datetime(tseries)
has_us = (tseries.dt.microsecond != 0).any()
ax.xaxis.set_major_locator(mdates.AutoDateLocator(minticks=5, maxticks=10))
if has_us:
# 예: 12:34:56.78 (마이크로초 6자리 중 앞 2자리만 표시)
def short_ms(x, pos):
s = mdates.num2date(x).strftime("%H:%M:%S.%f")
return s[:-4] # 뒤 4자리 잘라 두 자리만 남김
ax.xaxis.set_major_formatter(FuncFormatter(short_ms))
else:
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
plt.setp(ax.get_xticklabels(), rotation=15, ha="right")
def ensure_dir(path):
if path and not os.path.exists(path):
os.makedirs(path, exist_ok=True)
def should_spread_for_day(df_day: pd.DataFrame, day_key: pd.Timestamp) -> bool:
"""
날짜 규칙:
- (해당 연도) 8월 4일 이전: 무조건 펼치기(True)
- (해당 연도) 8월 11일 이후: 펼치기 금지(False, 기록된 대로)
"""
year = day_key.year
cut_a = pd.Timestamp(f"{year}-08-04")
cut_b = pd.Timestamp(f"{year}-08-11")
if day_key < cut_a:
return True
if day_key >= cut_b:
return False
# 자동 판별 구간
t = pd.to_datetime(df_day[TIME_COL])
no_us = (t.dt.microsecond == 0).all()
has_dups = t.duplicated(keep=False).any()
return bool(no_us and has_dups)
def plot_one_day(df_day: pd.DataFrame, day_key: pd.Timestamp):
# 유입 순서 보존 + 정렬
df_day = df_day.copy()
df_day['_ord'] = np.arange(len(df_day))
df_day = df_day.sort_values([TIME_COL, '_ord'], kind='mergesort')
# 날짜/데이터 조건에 따라 시간열 결정
if should_spread_for_day(df_day, day_key):
t_plot = build_plot_time_by_timestamp(df_day, TIME_COL, fallback='median')
else:
t_plot = pd.to_datetime(df_day[TIME_COL])
# 숫자화 & 스무딩
x = moving_average(pd.to_numeric(df_day[X_COL], errors="coerce").astype(float), SMOOTH_WINDOW)
y = moving_average(pd.to_numeric(df_day[Y_COL], errors="coerce").astype(float), SMOOTH_WINDOW)
z = moving_average(pd.to_numeric(df_day[Z_COL], errors="coerce").astype(float), SMOOTH_WINDOW)
mag = np.sqrt(x**2 + y**2 + z**2) if SHOW_MAGNITUDE else None
# tz 제거 (있을 경우) 후 바로 datetime Series 사용
t_dt = pd.to_datetime(t_plot).dt.tz_localize(None)
fig, ax = plt.subplots(figsize=(12, 6))
fig.subplots_adjust(right=0.82)
# 창 제목에 날짜 표기(창 분리 확인용)
try:
fig.canvas.manager.set_window_title(f"{day_key.strftime('%Y-%m-%d')} — Gravity")
except Exception:
pass
lines, labels = [], []
ln_x, = ax.plot(t_dt, x, linestyle="-", marker="o", markersize=3, label="x")
lines.append(ln_x); labels.append("x")
ln_y, = ax.plot(t_dt, y, linestyle="-", marker="o", markersize=3, label="y")
lines.append(ln_y); labels.append("y")
ln_z, = ax.plot(t_dt, z, linestyle="-", marker="o", markersize=3, label="z")
lines.append(ln_z); labels.append("z")
if SHOW_MAGNITUDE and mag is not None:
ln_m, = ax.plot(t_dt, mag, linestyle="-", marker="o", markersize=3, label="|g|")
lines.append(ln_m); labels.append("|g|")
ax.set_xlabel("Time of day")
ax.set_ylabel("Gravity (m/s²)")
ax.set_title(f"GRAVITY — {day_key.strftime('%Y-%m-%d')} (x, y, z)")
ax.grid(True, alpha=0.3)
setup_time_of_day_axis(ax, t_dt)
ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1.0))
# 체크박스 (figure에 부착 + draw_idle + GC 방지)
rax = fig.add_axes([0.84, 0.4, 0.12, 0.2])
states = [ln.get_visible() for ln in lines]
check = CheckButtons(rax, labels, states)
def on_check(label):
idx = labels.index(label)
ln = lines[idx]
ln.set_visible(not ln.get_visible())
fig.canvas.draw_idle()
check.on_clicked(on_check)
fig._lines = lines; fig._labels = labels; fig._check = check # 참조 보존
plt.tight_layout(rect=(0, 0, 0.82, 1))
return fig # 메인에서 fig.show() 호출용
def main():
df = pd.read_excel(EXCEL_PATH, sheet_name=SHEET_NAME)
# 시간 파싱 (예외 포맷 보정)
if not np.issubdtype(df[TIME_COL].dtype, np.datetime64):
df[TIME_COL] = df[TIME_COL].astype(str).str.strip()
df[TIME_COL] = df[TIME_COL].str.replace(
r"^(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}):(\d+)$",
r"\1.\2", regex=True
)
df[TIME_COL] = pd.to_datetime(df[TIME_COL], errors="coerce", infer_datetime_format=True)
# 유효행만 사용
df = df.dropna(subset=[TIME_COL, X_COL, Y_COL, Z_COL]).copy()
# ✔ 날짜 키 생성 (정규화해서 00:00 기준으로 같은 날 묶기)
df['__date__'] = pd.to_datetime(df[TIME_COL]).dt.normalize()
# 날짜별로 개별 figure 생성 후 즉시 show()
figs = []
for day_key, df_day in df.groupby('__date__', sort=True):
fig = plot_one_day(df_day, day_key)
figs.append(fig)
try:
fig.show() # 백엔드에 따라 창 분리를 확실히 함
except Exception:
pass
plt.show() # 일부 백엔드는 마지막에 한 번 더 호출 필요
if __name__ == "__main__":
main()