如何在Python无人机高度折线图中添加飞行阶段分类标签?
无人机高度与飞行阶段折线图实现方案
方法一:按飞行阶段颜色编码折线
通过颜色区分不同飞行阶段的折线段,直观展示阶段变化与高度的关联。
示例代码(Python + Matplotlib)
import pandas as pd import matplotlib.pyplot as plt # 加载数据集(替换为你的实际数据路径或加载逻辑) data = pd.DataFrame({ 'time (s)': [1,2,50,51,200,201,202,203,250,251,300,301], 'phase': ['take off','take off','cruise','cruise','landing','landing','take off','take off','cruise','cruise','landing','landing'], 'altitude': [10,20,500,500,20,10,10,20,500,500,20,10] }) # 定义阶段-颜色映射 phase_colors = { 'take off': '#FF6B6B', 'cruise': '#4ECDC4', 'landing': '#FFE66D' } plt.figure(figsize=(12,6)) # 识别阶段切换点 data['phase_shift'] = data['phase'] != data['phase'].shift() shift_indices = data[data['phase_shift']].index.tolist() shift_indices.append(len(data)) # 分段绘制不同颜色的折线 for i in range(len(shift_indices)-1): start_idx = shift_indices[i] end_idx = shift_indices[i+1] segment = data.iloc[start_idx:end_idx] current_phase = segment['phase'].iloc[0] # 仅在第一次出现阶段时添加图例项 plt.plot(segment['time (s)'], segment['altitude'], color=phase_colors[current_phase], linewidth=2, label=current_phase if i == 0 else "") # 在阶段中间位置添加文本标注 for phase in data['phase'].unique(): phase_segment = data[data['phase'] == phase] mid_time = phase_segment['time (s)'].mean() mid_alt = phase_segment['altitude'].mean() plt.text(mid_time, mid_alt, phase, fontsize=12, ha='center', va='center', bbox=dict(facecolor='white', alpha=0.8)) # 图表基础设置 plt.xlabel('Time (s)', fontsize=12) plt.ylabel('Altitude', fontsize=12) plt.title('UAV Altitude vs Flight Phase', fontsize=14) plt.legend(title='Flight Phase') plt.grid(alpha=0.3) plt.tight_layout() plt.show()
方法二:标注阶段起始/变化节点
在折线图上标记阶段切换的时间点,并用文本标注对应阶段,适合突出阶段转换的关键节点。
示例代码
import pandas as pd import matplotlib.pyplot as plt data = pd.DataFrame({ 'time (s)': [1,2,50,51,200,201,202,203,250,251,300,301], 'phase': ['take off','take off','cruise','cruise','landing','landing','take off','take off','cruise','cruise','landing','landing'], 'altitude': [10,20,500,500,20,10,10,20,500,500,20,10] }) plt.figure(figsize=(12,6)) # 绘制基础高度折线 plt.plot(data['time (s)'], data['altitude'], color='gray', linewidth=2, label='Altitude') # 筛选阶段切换点 data['phase_shift'] = data['phase'] != data['phase'].shift() shift_points = data[data['phase_shift']] # 标记切换节点并添加阶段标注 for _, row in shift_points.iterrows(): plt.scatter(row['time (s)'], row['altitude'], color='red', s=80, zorder=5) # 偏移标注位置避免遮挡折线 plt.text(row['time (s)'] + 2, row['altitude'] + 10, row['phase'], fontsize=11, ha='left', va='bottom') # 图表基础设置 plt.xlabel('Time (s)', fontsize=12) plt.ylabel('Altitude', fontsize=12) plt.title('UAV Altitude with Phase Change Markers', fontsize=14) plt.legend() plt.grid(alpha=0.3) plt.tight_layout() plt.show()
实用提示
- 若数据集是连续时间序列,方法一的颜色编码展示更流畅;若时间点间隔较大,方法二的节点标注更清晰
- 可根据需求调整颜色映射、标注位置、折线粗细等样式,优化图表可读性
内容的提问来源于stack exchange,提问作者user20040937
相关产品推荐
相关产品推荐

