使用Seaborn/Plotly绘制心率步数与咖啡摄入关联图表的优化问题
问题排查与优化方案
现有代码的核心问题
- 字段匹配错误:代码中使用了不存在的
medication字段作为style参数,你的数据集仅提供了coffee字段作为咖啡摄入状态标识,字段不匹配会直接导致绘图逻辑错误。 - 时间字段识别异常:
created是数据集的索引字段,直接作为x轴参数传入时Seaborn无法正确识别为时间类型,会出现刻度重叠、排序混乱的问题。 - 多维度呈现逻辑错误:你需要同时展示心率、步数、咖啡节点三类信息,单条折线的呈现逻辑完全不符合需求。
- 缺失值未处理:
steps字段存在大量NaN值,直接绘图会出现折线断裂、数据缺失的问题。
优化实现方案
Seaborn静态图实现
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd # 数据预处理 df = tester.reset_index() # 将时间索引转为普通列 df['created'] = pd.to_datetime(df['created']) # 强制转换为时间格式 df['coffee'] = df['coffee'].astype('category') # 咖啡状态转为分类变量,方便区分样式 df['steps'] = df['steps'].fillna(method='pad') # 可根据需求选择填充/插值/直接置0 # 创建双行子图,分别承载心率、步数数据,避免量级差异导致可读性下降 fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8), sharex=True) # 绘制心率折线,同时用颜色和样式区分咖啡状态 sns.lineplot(x="created", y="heartRate", hue="coffee", style="coffee", data=df, ax=ax1, linewidth=2) ax1.set_ylabel('心率') ax1.set_title('心率与咖啡摄入关联趋势') # 可选:在咖啡状态非0的时间点加虚线标记,突出摄入节点 for time in df[df['coffee'] != 0]['created']: ax1.axvline(x=time, color='red', linestyle='--', alpha=0.3) # 绘制步数折线 sns.lineplot(x="created", y="steps", data=df, ax=ax2, linewidth=2, color='green') ax2.set_ylabel('步数') ax2.set_xlabel('时间') ax2.set_title('步数变化趋势') # 自动调整时间刻度避免重叠 fig.autofmt_xdate() plt.tight_layout() plt.show()
Plotly交互式图实现(更适合查看时间序列细节)
import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd # 数据预处理 df = tester.reset_index() df['created'] = pd.to_datetime(df['created']) df['steps'] = df['steps'].fillna(method='pad') # 创建双行子图 fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=('心率与咖啡摄入关联趋势', '步数变化趋势')) # 分状态绘制心率折线 color_map = {0: 'blue', 1: 'orange', 2: 'red'} for status in df['coffee'].unique(): temp_df = df[df['coffee'] == status] fig.add_trace(go.Scatter(x=temp_df['created'], y=temp_df['heartRate'], name=f'咖啡状态{status}', line=dict(color=color_map[status], width=2)), row=1, col=1) # 添加咖啡摄入节点标记线 for time in df[df['coffee'] != 0]['created']: fig.add_vline(x=time, line_dash="dash", line_color="red", opacity=0.3, row=1, col=1) # 绘制步数折线 fig.add_trace(go.Scatter(x=df['created'], y=df['steps'], name='步数', line=dict(color='green', width=2)), row=2, col=1) # 布局调整 fig.update_layout(height=700, width=1000, title_text="健康数据与咖啡摄入关联分析") fig.update_xaxes(title_text="时间", row=2, col=1) fig.update_yaxes(title_text="心率", row=1, col=1) fig.update_yaxes(title_text="步数", row=2, col=1) fig.show()
内容的提问来源于stack exchange,提问作者LeCoda
相关产品推荐
相关产品推荐

