从仿真到论文图表:SUMO+Python+Matplotlib实战,让你的交通流数据可视化起来

发布时间:2026/6/2 9:59:24

从仿真到论文图表:SUMO+Python+Matplotlib实战,让你的交通流数据可视化起来 SUMOPythonMatplotlib科研级交通流可视化全流程指南当SUMO仿真跑出理想数据后如何将这些原始数据转化为学术期刊认可的图表这个问题困扰着许多交通工程领域的研究者。本文将带你从TraCI数据提取到Matplotlib图表美化构建完整的科研可视化工作流。1. 数据采集与预处理在开始绘图前我们需要从SUMO仿真中提取有效数据。TraCI接口提供了丰富的实时数据获取方法但原始数据往往需要清洗才能用于可视化。import traci import pandas as pd def collect_vehicle_data(sumocfg_path, simulation_steps): traci.start([sumo-gui, -c, sumocfg_path]) vehicle_data [] for step in range(simulation_steps): traci.simulationStep() current_time traci.simulation.getTime() for veh_id in traci.vehicle.getIDList(): pos traci.vehicle.getPosition(veh_id) speed traci.vehicle.getSpeed(veh_id) lane traci.vehicle.getLaneID(veh_id) vehicle_data.append({ time: current_time, id: veh_id, x: pos[0], y: pos[1], speed: speed, lane: lane }) traci.close() return pd.DataFrame(vehicle_data)常见数据问题及解决方案问题类型表现特征处理方法数据缺失某些时间步车辆信息丢失线性插值或前后值填充坐标偏移不同路段坐标系不统一转换为相对路网坐标采样不均高频数据导致绘图冗余按固定时间间隔降采样提示建议在数据采集阶段就保存原始CSV文件避免重复仿真消耗计算资源2. 时空轨迹可视化技巧时空图是交通流研究的核心图表之一能直观展示车辆在时间和空间维度的运动规律。2.1 基础时空图绘制import matplotlib.pyplot as plt def plot_spacetime(df, lane_id): lane_df df[df[lane] lane_id] plt.figure(figsize(10, 6)) for veh_id, group in lane_df.groupby(id): plt.plot(group[time], group[x], linewidth1.5, alpha0.7) plt.xlabel(Time (s)) plt.ylabel(Position (m)) plt.title(fSpace-Time Diagram for Lane {lane_id}) plt.grid(alpha0.3) plt.tight_layout() return plt2.2 学术级图表优化要让图表达到发表质量需要关注以下细节色彩方案使用色盲友好配色如viridis图例排版控制图例数量避免遮挡关键曲线标注清晰添加比例尺和关键参数说明字体规范统一使用Times New Roman或Arialfrom matplotlib.colors import ListedColormap def enhanced_spacetime(df, lane_id): cmap ListedColormap(plt.get_cmap(viridis).colors[::20]) fig, ax plt.subplots(figsize(12, 7)) for i, (veh_id, group) in enumerate(df.groupby(id)): color cmap(i % 256) ax.plot(group[time], group[x], colorcolor, linewidth1.2) ax.set_xlabel(Time (s), fontsize12, fontnameArial) ax.set_ylabel(Position (m), fontsize12, fontnameArial) ax.tick_params(axisboth, whichmajor, labelsize10) fig.savefig(spacetime.png, dpi300, bbox_inchestight)3. 流量-密度关系分析宏观基本图MFD是评价路网性能的重要工具下面演示如何从微观数据计算宏观参数def calculate_macroscopic(df, interval60): time_bins pd.cut(df[time], binsrange(0, int(df[time].max())interval, interval), rightFalse) agg_df df.groupby(time_bins).agg({ id: nunique, speed: mean }).rename(columns{id: flow, speed: avg_speed}) agg_df[density] agg_df[flow] / (df[x].max()/1000) # 车辆/km agg_df[flow] agg_df[flow] * 3600 / interval # 车辆/h return agg_df.dropna()可视化对比方案经典Greenshields模型拟合from scipy.optimize import curve_fit def greenshields(k, k_j, u_f): return u_f * k * (1 - k/k_j) params, _ curve_fit(greenshields, agg_df[density], agg_df[flow], p0[150, 80])三维时空密度热图import numpy as np from matplotlib.colors import LogNorm def density_heatmap(df, time_step5, space_step10): time_bins np.arange(0, df[time].max()time_step, time_step) space_bins np.arange(0, df[x].max()space_step, space_step) heatmap, xedges, yedges np.histogram2d( df[time], df[x], bins[time_bins, space_bins], weights1/df[speed]) plt.imshow(heatmap.T, originlower, extent[xedges[0], xedges[-1], yedges[0], yedges[-1]], cmaphot, normLogNorm()) plt.colorbar(labelDensity (veh/m))4. 多维度数据协同可视化高水平论文往往需要展示数据多个维度的关联性这里介绍两种高级技巧4.1 动画轨迹展示from matplotlib.animation import FuncAnimation def create_animation(df): fig, ax plt.subplots(figsize(10, 6)) scat ax.scatter([], [], s50, c[], cmapjet) def init(): ax.set_xlim(df[x].min()-50, df[x].max()50) ax.set_ylim(df[y].min()-50, df[y].max()50) return scat, def update(frame): frame_df df[np.abs(df[time]-frame) 0.1] scat.set_offsets(frame_df[[x, y]].values) scat.set_array(frame_df[speed].values) return scat, ani FuncAnimation(fig, update, framesnp.linspace(0, df[time].max(), 100), init_funcinit, blitTrue, interval50) ani.save(trajectory.mp4, writerffmpeg, dpi200)4.2 交互式可视化import plotly.express as px def interactive_plot(df): fig px.scatter(df, xtime, yx, colorspeed, hover_data[id, lane], color_continuous_scaleViridis) fig.update_layout( hovermodex unified, xaxis_titleTime (s), yaxis_titlePosition (m) ) fig.show()5. 学术图表规范与输出最后阶段需要确保图表符合学术出版要求期刊常见格式要求TIFF/PDF/矢量图格式分辨率≥300dpi字体大小≥8pt线条粗细≥0.5ptdef save_for_publication(plt, filename): plt.savefig( f{filename}.pdf, formatpdf, dpi300, bbox_inchestight, pad_inches0.1, metadata{ Title: filename, Author: Your Name, Subject: Traffic Simulation Results, Keywords: SUMO, Traffic Flow, Visualization } )典型问题排查表问题现象可能原因解决方案图表模糊保存为JPEG格式改用PDF或TIFF格式文字错位字体未嵌入使用通用字体或转曲颜色失真RGB色彩模式转换为CMYK模式文件过大未压缩位图使用LZW压缩或矢量图

相关新闻