社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何使用Python在地图上绘制线字符串?

Rebecka • 4 年前 • 1682 次点击  

我有一些来自Lng和lat的坐标,我把它们组合成一条线串。

线串由2个点组成。从某一点来说 starting=origin 从一个角度来看 ending = destination .

这是Linestring列的代码

erg2['Linestring'] = erg2.apply(lambda x: LineString([(x['latitude_origin'], x['longitude_origin']), (x['latitude_destination'], x['longitude_destination'])]), axis = 1)

我正在尽一切努力绘制从起点到终点的线串,但没有任何好结果\

你会帮我很多忙的\

这是数据帧 erg2 使用lng和lat以及组合管线串。。。 我怎么能在地图上画出来呢。“起点”和“终点”列中的数字是城市的位置ID。。

作为一名经验丰富的程序员,你会怎么想。两个点是分散的还是组合的线串?? 下面是我的数据框。头()。希望读者友好:) 通常df有[19600行x 8列]

起源 目的地 移动 经度与原点 纬度与原点
88 88 20 13.481016 52.457055
88 89 0 13.481016 52.457055
88 110 0 13.481016 52.457055
88 111 0 13.481016 52.457055
88 112 0 13.481016 52.457055
87 83 0 13.479667 52.479600
目的地经度 目的地纬度 线绳
13.481016 52.457055 线串(52.45705489204205 13.4810161067992。。。
13.504075 52.443923 线串(52.45705489204205 13.4810161067992。。。
13.613772 52.533194 线串(52.45705489204205 13.4810161067992。。。
13.586891 52.523562 线串(52.45705489204205 13.4810161067992。。。
13.559341 52.507418 线串(52.45705489204205 13.4810161067992。。。
13.481016 52.457055 线串(52.45705489204205 13.4810161067992。。。

我正在尝试用@RobRaymond中geopandas的示例代码绘制这些线

结果显示了一些没有意义的线条。。 这是输出:

enter image description here

所有的行在悬停中都有这样的描述,都从87-。。。 在我的数据框中,你可以看到我们有origin 88等。。。

根据动作绘制线条也很重要。因为不需要绘制零运动图。。。 我真的希望我能把问题说清楚。这真的让我有点不知所措。。。

提前谢谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130218
文章 [ 2 ]  |  最新文章 4 年前
Rob Raymond
Reply   •   1 楼
Rob Raymond    5 年前
import requests, io, json
import geopandas as gpd
import shapely.geometry
import pandas as pd
import numpy as np
import itertools
import plotly.express as px

# get some public addressess - hospitals.  data that has GPS lat / lon
dfhos = pd.read_csv(io.StringIO(requests.get("http://media.nhschoices.nhs.uk/data/foi/Hospital.csv").text),
    sep="¬",engine="python",).loc[:, ["OrganisationName", "Latitude", "Longitude"]]

a = np.arange(len(dfhos))
np.random.shuffle(a)
# establish N links between hospitals
N = 10
df = (
    pd.DataFrame({0:a[0:N], 1:a[25:25+N]}).merge(dfhos,left_on=0,right_index=True)
    .merge(dfhos,left_on=1, right_index=True, suffixes=("_origin", "_destination"))
)

# build a geopandas data frame that has LineString between two hospitals
gdf = gpd.GeoDataFrame(
    data=df,
    geometry=df.apply(
        lambda r: shapely.geometry.LineString(
            [(r["Longitude_origin"], r["Latitude_origin"]),
             (r["Longitude_destination"], r["Latitude_destination"]) ]), axis=1)
)

# sample code https://plotly.com/python/lines-on-mapbox/#lines-on-mapbox-maps-from-geopandas
lats = []
lons = []
names = []

for feature, name in zip(gdf.geometry, gdf["OrganisationName_origin"] + " - " + gdf["OrganisationName_destination"]):
    if isinstance(feature, shapely.geometry.linestring.LineString):
        linestrings = [feature]
    elif isinstance(feature, shapely.geometry.multilinestring.MultiLineString):
        linestrings = feature.geoms
    else:
        continue
    for linestring in linestrings:
        x, y = linestring.xy
        lats = np.append(lats, y)
        lons = np.append(lons, x)
        names = np.append(names, [name]*len(y))
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        names = np.append(names, None)

fig = px.line_mapbox(lat=lats, lon=lons, hover_name=names)

fig.update_layout(mapbox_style="stamen-terrain",
                  mapbox_zoom=4,
                  mapbox_center_lon=gdf.total_bounds[[0,2]].mean(),
                  mapbox_center_lat=gdf.total_bounds[[1,3]].mean(),
                  margin={"r":0,"t":0,"l":0,"b":0}
                 )

简化版

  • 使用医院间链接的dataframe作为样本数据
  • 阴谋地 文件和标签明确指出需要用 None 在传递给 px.line_mapbox() .使用 努比 没有必要建造 线绳 使用 地质纳达斯 或 匀称
# plotly takes array delimited with None between lines. Use numpy padding and shaping to generate this array
# from pair of features
def line_array(df, cols):
    return np.pad(df.loc[:,cols].values, [(0, 0), (0, 1)], constant_values=None).reshape(1,(len(df)*3))[0]
    

fig = px.line_mapbox(lat=line_array(df, ["Latitude_origin", "Latitude_destination"]), 
                     lon=line_array(df, ["Longitude_origin", "Longitude_destination"]),
                     hover_name=line_array(df, ["OrganisationName_origin", "OrganisationName_destination"]),
)

fig.update_layout(mapbox_style="stamen-terrain",
                  mapbox_zoom=4,
                  mapbox_center_lon=df.loc[:,["Longitude_origin","Longitude_destination"]].mean().mean(),
                  mapbox_center_lat=df.loc[:,["Latitude_origin","Latitude_destination"]].mean().mean(),
                  margin={"r":0,"t":0,"l":0,"b":0}
                 )


enter image description here

r-beginners
Reply   •   2 楼
r-beginners    5 年前

使用 examples 以及来自官方的数据 reference ,我已经替换了您的问题,并确定了阻止绘制线段的问题。您需要指定一列文本,指示要设置颜色的组。因此,将颜色设置为数据中的组键列。

import plotly.express as px
import pandas as pd

df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df_airports.head()

df_flight_paths = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_aa_flight_paths.csv')
df_flight_paths.sort_values('cnt', ascending=False, inplace=True)

df_flight_paths = df_flight_paths.query("airport2 in ['DFW','LAX']")

df_flight_paths.head()
start_lat   start_lon   end_lat     end_lon     airline     airport1    airport2    cnt
33  33.942536   -118.408074     32.895951   -97.0372    AA  LAX     DFW     914
50  29.533694   -98.469778  32.895951   -97.0372    AA  SAT     DFW     826
44  41.979595   -87.904464  32.895951   -97.0372    AA  ORD     DFW     825
20  30.194533   -97.669872  32.895951   -97.0372    AA  AUS     DFW     820
19  33.640444   -84.426944  32.895951   -97.0372    AA  ATL     DFW     580

fig = px.line_mapbox(df_flight_paths,
                     lat="start_lat", 
                     lon="start_lon", 
                     color="airport2",
                     hover_name="airport1",
                     #animation_frame="time",
                     center =dict(lon=-97.0,lat=38.0),
                     zoom=3, height=600
                    )

fig.update_layout(mapbox_style="stamen-terrain",
                  mapbox_zoom=4,
                  mapbox_center_lon=-97.0,
                  mapbox_center_lat=38.0,
                  margin={"r":0,"t":0,"l":0,"b":0}
                 )

fig.show()

enter image description here