Python交通密度可视化:基于AADT的公路路段着色线路图工具选型
Awesome question! For your specific task of turning highway segment data (with AADT and lat/lon coordinates) into color-coded lines—where high AADT values show up as red and low values as green—here are the top Python toolkits you should check out, along with why they’re a fit and quick code snippets to get you started:
GeoPandas + Matplotlib (Static, Geospatial-First Approach)
This is my go-to for static, geospatial plots that are easy to customize and export. GeoPandas simplifies handling geographic data, letting you convert your CSV’s lat/lon pairs into proper line geometries, while Matplotlib handles the color mapping seamlessly.
Quick Example Code
import geopandas as gpd from shapely.geometry import LineString import matplotlib.pyplot as plt # Load your CSV (assuming columns: segment_id, lon, lat, AADT) df = gpd.read_file("highway_data.csv") # Group data by segment and create LineString geometries segment_groups = df.groupby("segment_id") line_geometries = [LineString(zip(group["lon"], group["lat"])) for _, group in segment_groups] geo_df = gpd.GeoDataFrame(segment_groups["AADT"].first(), geometry=line_geometries) # Plot with color mapped to AADT (RdYlGn_r reverses the default green-red scale) fig, ax = plt.subplots(figsize=(10, 8)) geo_df.plot( column="AADT", cmap="RdYlGn_r", linewidth=2, ax=ax, legend=True, legend_kwds={"label": "Annual Average Daily Traffic (AADT)"} ) plt.title("Highway Segment AADT Distribution") plt.show()
Plotly (Interactive, Explorative Visualizations)
If you want an interactive plot where users can zoom, pan, and hover over segments to see exact AADT values, Plotly is perfect. It supports geospatial line plots out of the box and makes color mapping straightforward.
Quick Example Code
import plotly.express as px import pandas as pd # Load CSV and ensure points are ordered correctly per segment df = pd.read_csv("highway_data.csv") df = df.sort_values(["segment_id", "point_order"]) # Add a point_order column if needed to sequence points # Create interactive geospatial line plot fig = px.line_geo( df, lat="lat", lon="lon", color="AADT", color_continuous_scale=px.colors.diverging.RdYlGn[::-1], # Reverse for high=red, low=green line_group="segment_id", hover_name="segment_id", hover_data={"AADT": True} ) # Update map projection and layout fig.update_geos(projection_type="mercator") fig.update_layout(title="Interactive Highway AADT Visualization") fig.show()
Folium (Interactive Web Maps with OpenStreetMap Basemaps)
For visualizations layered on top of a live web map (like OpenStreetMap), Folium is the way to go. It lets you add color-coded highway segments directly to a map that users can interact with in a browser.
Quick Example Code
import folium import pandas as pd from shapely.geometry import LineString from matplotlib.colors import Normalize, to_hex import matplotlib.cm as cm # Load CSV and normalize AADT values for color mapping df = pd.read_csv("highway_data.csv") norm = Normalize(vmin=df["AADT"].min(), vmax=df["AADT"].max()) cmap = cm.get_cmap("RdYlGn_r") # Create base map centered on your highway data map_center = [df["lat"].mean(), df["lon"].mean()] m = folium.Map(location=map_center, zoom_start=10) # Add each highway segment to the map with color-coded AADT for seg_id, group in df.groupby("segment_id"): coords = list(zip(group["lat"], group["lon"])) aadt_value = group["AADT"].iloc[0] segment_color = to_hex(cmap(norm(aadt_value))) folium.PolyLine( locations=coords, color=segment_color, weight=3, tooltip=f"Segment {seg_id}: AADT = {aadt_value}" ).add_to(m) # Add a color bar legend from folium.plugins import LinearColormap colormap = LinearColormap( colors=["green", "yellow", "red"], vmin=df["AADT"].min(), vmax=df["AADT"].max(), caption="Annual Average Daily Traffic (AADT)" ) colormap.add_to(m) # Save map as HTML file m.save("highway_aadt_map.html")
Final Recommendation
Choose based on your end goal:
- GeoPandas + Matplotlib: Best for static, publication-ready plots.
- Plotly: Ideal if you need interactive exploration (hover, zoom, pan).
- Folium: Perfect for embedding your visualization in a web map with real-world context.
内容的提问来源于stack exchange,提问作者ger33

