如何结合截止时间绘制行程时长可视化图表?
解决方案:添加彩色虚线与区块文本标注
1. 补充数据处理,提取起始/结束区块
原代码仅计算了时间区间,需要额外提取每行对应的起始和结束区块名称,后续用于标注:
import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter # 原始数据 df = pd.DataFrame({'blk1': {'a': '12h45', 'b': None, 'c': None, 'd': None}, 'blk2': {'a': None, 'b': None, 'c': '13h15', 'd': '15h15'}, 'blk3': {'a': None, 'b': '12h10', 'c': None, 'd': None}, 'blk4': {'a': None, 'b': '15h45', 'c': '13h30', 'd': None}, 'blk5': {'a': '13h30', 'b': None, 'c': None, 'd': '16h15'}, 'deadline': {'a': '13h00', 'b': '14h30', 'c': '15h00', 'd': '15h45'}}) # 移除deadline列,处理时间格式 df1 = df.drop(columns='deadline') df_time = df1.apply(lambda x: pd.to_datetime(x, format='%Hh%M')) # 提取每行的起始/结束区块及对应时间 def get_start_end(row): non_null = row.dropna() sorted_vals = non_null.sort_values() return pd.Series([sorted_vals.index[0], sorted_vals.iloc[0], sorted_vals.index[1], sorted_vals.iloc[1]], index=['start_blk', 'start_time', 'end_blk', 'end_time']) df_processed = df_time.apply(get_start_end, axis=1) df_processed['duration'] = df_processed['end_time'] - df_processed['start_time'] df_processed = df_processed.reset_index().rename(columns={'index': 'element'})
2. 绘制图表,添加虚线与标注
循环遍历每行数据,实现彩色虚线和区块转换文本的添加:
# 给每个元素分配专属颜色 colors = ['#ff7f0e', '#1f77b4', '#2ca02c', '#d62728'] fig, ax = plt.subplots(figsize=(10, 2)) for idx, row in df_processed.iterrows(): # 绘制基础水平条形 ax.barh(y=row['element'], width=row['duration'], left=row['start_time'], ec='k', color='white', height=0.2) # 绘制彩色水平虚线 ax.plot([row['start_time'], row['end_time']], [row['element'], row['element']], linestyle='--', color=colors[idx], linewidth=2) # 在时间区间中点添加区块转换标注 mid_time = row['start_time'] + row['duration']/2 ax.text(mid_time, row['element'], f"{row['start_blk']}到{row['end_blk']}", ha='center', va='center', fontsize=10) # 设置x轴时间格式为小时:分钟 date_form = DateFormatter("%H:%M") ax.xaxis.set_major_formatter(date_form) ax.set_xlim(df_processed['start_time'].min(), df_processed['end_time'].max()) plt.tight_layout() plt.show()
核心逻辑说明
- 区块提取:通过
get_start_end函数筛选每行非空列,按时间排序后得到起始/结束区块名称。 - 彩色虚线:为每个元素分配独立颜色,用
plot绘制水平虚线连接起始和结束时间点。 - 文本标注:计算时间区间中点,确保标注文本居中显示在对应元素的时间轴上方。
内容的提问来源于stack exchange,提问作者VERBOSE
相关产品推荐
相关产品推荐

