You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib散点图中为每个进程起止点连线的实现方法

实现进程活跃时间段的可视化

我明白你想要的效果——把每个进程的活跃时间段用水平线段展示出来,这样在大数据集里一眼就能看清每个进程什么时候活跃、什么时候空闲对吧?你的现有代码只画了散点,所以看不到时间段的连线,咱们来改一改:

修改后的代码

import matplotlib.pyplot as plt

# 整理进程数据,这样扩展更多进程更方便
process_data = {
    "process-1": {
        "start_times": [32, 30, 40, 50, 60, 78],
        "live_durations": [1, 3, 2, 1, 2, 4]
    },
    "process-2": {
        "start_times": [22, 25, 45, 55, 60, 72],
        "live_durations": [1, 3, 2, 1, 2, 4]
    }
}

plt.figure(figsize=(10, 4))  # 调整图表大小,更适合展示时间段
y_tick_positions = []
y_tick_labels = []

# 遍历每个进程,绘制活跃时间段的水平线
for idx, (process_name, data) in enumerate(process_data.items(), start=1):
    y_pos = idx
    y_tick_positions.append(y_pos)
    y_tick_labels.append(process_name)
    
    # 计算每个活跃周期的结束时间
    end_times = [start + duration for start, duration in zip(data["start_times"], data["live_durations"])]
    
    # 批量绘制水平线:指定y轴位置、起始时间、结束时间
    plt.hlines(y=y_pos, xmin=data["start_times"], xmax=end_times, 
               color='steelblue', linewidth=3, alpha=0.7)
    
    # 可选:保留起止点的散点标记,让每个周期的开始/结束更醒目
    plt.scatter(data["start_times"], [y_pos]*len(data["start_times"]), 
                color='darkblue', zorder=5, s=30)
    plt.scatter(end_times, [y_pos]*len(end_times), 
                color='darkblue', zorder=5, s=30)

# 优化坐标轴显示
plt.xlabel('time (s)', fontsize=12)
plt.yticks(y_tick_positions, y_tick_labels, fontsize=12)
plt.title('Process Active Time Periods', fontsize=14)
plt.grid(axis='x', linestyle='--', alpha=0.6)  # 添加x轴网格,方便对应时间点
plt.tight_layout()  # 自动调整布局,避免标签被截断
plt.show()

关键改动说明

  • 数据结构化:把进程数据整理成字典,后续添加更多进程时只需补充字典条目,代码扩展性更强
  • 用水平线替代散点连线:使用plt.hlines()批量绘制每个活跃周期的水平线段,这比循环调用plt.plot()更高效,也更贴合需求
  • 优化y轴可读性:将y轴刻度替换为进程名称,替代原来的数字,直观对应每个进程
  • 视觉优化:添加标题、x轴网格,调整图表尺寸,让整体展示更清晰;可选的散点标记能突出每个活跃周期的起止点

这样生成的图表会清晰展示每个进程的所有活跃时段,同一条y轴上两段水平线之间的空隙就是进程的空闲时间,大数据量下也能轻松分辨各进程的时间分布。

内容的提问来源于stack exchange,提问作者Zeeshan Hayat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:05:50