我在csv中有3个主要值(经度,纬度和速度)。使用Folium库,我可以用lon和lat度映射位置。我当前的代码是:
import pandas as pd
from geopy.geocoders import Nominatim
import folium
from pandas import *
import numpy as np
from matplotlib import cm
import folium
df = DataFrame({'lon': [9.899193, 9.899236, 9.899292, 9.899331, 9.899372, 9.899411, 9.89946, 9.899518, 9.899393, 9.899409, 9.899456, 9.899498, 9.89952, 9.899558, 9.8996, 9.899625, 9.899646, 9.899659, 9.899678, 9.899707, 9.899745, 9.899778], 'lat': [48.849231, 48.849201, 48.849163, 48.849128, 48.84909, 48.849056, 48.84901, 48.848968, 48.849018, 48.849014, 48.848979, 48.848949, 48.848926, 48.84888, 48.848831, 48.848789,48.848762, 48.848735, 48.848712, 48.848686,48.848655, 48.848632 ], 'speed' : [15, 25, 32, 45, 50, 75, 64, 32, 13, 23, 42, 13, 23, 42, 64, 32, 13, 23, 42, 13, 23, 42]})
ave_lt = sum(df['lat'])/len(df)
ave_lg = sum(df['lon'])/len(df)
points = zip(df['lat'], df['lon'])
points = list(points)
my_map = folium.Map(location=[ave_lt, ave_lg], zoom_start=14)
folium.PolyLine(points, color="red", weight=2.5, opacity=1).add_to(my_map)
my_map
直到这里它运行良好,并给我这样的输出: 但现在我也想将csv的speed属性放到当前地图上以生成色标(基于速度值)。例如,如果速度在0-20之间,则该行的部分为红色;如果速度在20-60之间,则为黄色;如果速度高于60,则该行为绿色。有可能在python中做到吗?有人可以帮我吗?我想得到这样的输出:
很抱歉这个问题,但是我是python新手,我真的需要这么做,谢谢!!非常感谢您的帮助!
答案 0 :(得分:1)
尝试一下:
首先,编写以下两个函数
def draw_polylines(points, speeds, map):
colors = [speed_color(x) for x in speeds]
n = len(colors)
# Need to have a corresponding color for each point
if n != len(points):
raise ValueError
i = 0
j = 1
curr = colors[0]
while i < n and j < n:
if colors[i] != colors[j]:
line = folium.PolyLine(points[i:j], color=curr, weight=2.5, opacity=1)
line.add_to(map)
curr = colors[j]
i = j
j += 1
if i < j:
folium.PolyLine(points[i:j], color=curr, weight=2.5, opacity=1).add_to(map)
def speed_color(speed):
if speed < 0:
raise ValueError
elif speed >= 0 and speed < 20:
return 'red'
elif speed >= 20 and speed < 60:
return 'yellow'
else:
return 'green'
然后,在一行之后
my_map = folium.Map(location=[ave_lt, ave_lg], zoom_start=14)
拨打电话
draw_polylines(points, df['speed'], my_map)
我在您提供的数据上进行了尝试,它似乎有效。绝对要自己检查一下。
从本质上讲,逐段确定线段颜色,并使用每种颜色的相应速度。如果每个点都没有速度,或者速度为负(编写更广泛的错误测试;数据通常不干净!),则此代码将引发错误。