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

如何在Python Datashader点画布上叠加路径与标记点?

问题需求

我需要绘制经纬度点,并在其上方展示A到B的最短路径线条。同时希望解决现有实现扩展性差的问题,以及了解如何高亮地图上的特定点(如起点和终点)。

当前实现代码

cvs = ds.Canvas(plot_width=3000, plot_height=3000, x_range=(minLon, maxLon), y_range=(minLat, maxLat))
cv1 = ds.Canvas(plot_width=3000, plot_height=3000, x_range=(minLon, maxLon), y_range=(minLat, maxLat))
agg = cvs.points(df, 'x', 'y')  # 绘制所有经纬度点的热力图
agg1 = cv1.line(positionsOfNodesInShortesPathDF, 'x', 'y', line_width=5)

img = ds.tf.set_background(ds.tf.shade(agg, how="cbrt", cmap=cc.fire), "black").to_pil() # 生成点图的栅格图像
path = ds.tf.set_background(ds.tf.shade(agg1, how="log", cmap=cc.fire), "black").to_pil() # 生成路径图的栅格图像

当前叠加方法

目前通过遍历像素将路径图背景设为透明,再与点图叠加:

newImage = []
for item in path.getdata():
    if item[:3] == (0, 0, 0):
        newImage.append((0, 0, 0, 0))
    else:
        newImage.append(item)

path.putdata(newImage)

im.alpha_composite(img, path).save("combined.png")

当前效果:
经纬度点与最短路径叠加效果


解决方案

1. 高效图层叠加方案(替代像素遍历)

无需分别生成两张图再手动处理透明,直接在Datashader层面合并图层,一次性导出即可,扩展性更强且避免坐标偏差:

# 共用同一个Canvas,确保坐标一致
cvs = ds.Canvas(plot_width=3000, plot_height=3000, x_range=(minLon, maxLon), y_range=(minLat, maxLat))

# 生成点图层
agg_points = cvs.points(df, 'x', 'y')
shaded_points = ds.tf.shade(agg_points, how="cbrt", cmap=cc.fire)

# 生成路径图层,将黑色背景转为透明(用nan替代)
agg_path = cvs.line(positionsOfNodesInShortesPathDF, 'x', 'y', line_width=5)
shaded_path = ds.tf.shade(agg_path, how="log", cmap=cc.fire)
shaded_path = shaded_path.where(shaded_path != 0)  # 黑色区域转为透明

# 合并图层:点图为底层,路径图叠加在上
combined = shaded_points + shaded_path

# 设置整体背景为黑色后导出
final_img = ds.tf.set_background(combined, "black").to_pil()
final_img.save("combined.png")

2. 高亮起点和终点

单独生成高亮点图层,叠加在最上层即可实现醒目效果:

import pandas as pd

# 假设起点坐标为(start_lon, start_lat),终点为(end_lon, end_lat)
highlight_df = pd.DataFrame({
    'x': [start_lon, end_lon],
    'y': [start_lat, end_lat]
})

# 生成高亮点图层,用更大尺寸和鲜明颜色(如黄色)
agg_highlight = cvs.points(highlight_df, 'x', 'y', size=20)
shaded_highlight = ds.tf.shade(agg_highlight, cmap=['yellow'])
shaded_highlight = shaded_highlight.where(shaded_highlight != 0)

# 合并所有图层:点图 -> 路径图 -> 高亮点图
combined = shaded_points + shaded_path + shaded_highlight
final_img = ds.tf.set_background(combined, "black").to_pil()
final_img.save("combined_with_highlight.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:00:07