使用plotly在地图框​​上绘制多边形

时间:2019-05-18 16:54:27

标签: plotly

我正在尝试使用scattermapbox绘制geojson几何图形。

这段代码成功地从geopandas转换了数据,以可用于以下目的:

from plotly.offline import download_plotlyjs, init_notebook_mode, 
plot, iplot
import plotly.graph_objs as go

mapbox_access_token = 'mykey'

import json

from_json = geopandas_gdf.to_json()
geoJSON = json.loads(from_json)

pts=[]#list of points defining boundaries of polygons
for  feature in geoJSON['features']:
    if feature['geometry']['type']=='Polygon':
        pts.extend(feature['geometry']['coordinates'][0])    
        pts.append([None, None])#mark the end of a polygon   

    elif feature['geometry']['type']=='MultiPolygon':
        for polyg in feature['geometry']['coordinates']:
            pts.extend(polyg[0])
            pts.append([None, None])#end of polygon
    else: raise ValueError("geometry type irrelevant for map") 

X, Y=zip(*pts)

我可以使用以下代码在blanc图上绘制此数据:

axis_style=dict(showline=False, 
            mirror=False, 
            showgrid=False, 
            zeroline=False,
            ticks='',
            showticklabels=False)
layout=dict(title='map',
            width=700, height=700, 
            autosize=False,
            xaxis=axis_style,
            yaxis=axis_style,
            hovermode='closest')
fig=dict(data=data, layout=layout)
plot(fig, filename='map')

但是我不能在scattermapbox上绘制它。尝试这样:

data = [
go.Scattermapbox(
    lat=X,
    lon=Y,
    line = go.scattermapbox.Line(width=5,
                                 color='red'))
    ]

layout = go.Layout(
autosize=True,
hovermode='closest',
mapbox=go.layout.Mapbox(
    accesstoken=mapbox_access_token,
    bearing=0,
    center=go.layout.mapbox.Center(
        lat=53,
        lon=0
    ),
    pitch=0,
    zoom=5
    ),
)

fig = go.Figure(data=data, layout=layout)
plot(fig, filename='Montreal Mapbox')

谢谢!

2 个答案:

答案 0 :(得分:0)

我已经做到了以下几点:

layout = go.Layout(
    height=1500,
    autosize=True,
    hovermode='closest',
    mapbox=dict(
        layers=[
            dict(
                sourcetype = 'geojson',
                source = geoJSON,
                type = 'fill',
                color = 'rgba(163,22,19,0.8)'
            )
        ],
        accesstoken=mapbox_access_token,
        bearing=0,
        center=dict(
            lat=53,
             lon=0
        ),
        pitch=0,
        zoom=5.2,
        style='light'
     ),
)

但是随后出现了另一个问题:如何将数据从json提供到悬停?

答案 1 :(得分:0)

回答您的第二个问题

通过使用传递到绘图的customdata中的data属性,将数据从JSON提供到悬停。

另外:您能否路由一个通用的json数据集,以便其他人可以轻松地运行您的代码块?

链接到customdata属性:https://plot.ly/python/reference/#scatter-customdata

Else,您可以使用textmode='markers + text'在悬停时显示来自text属性的数据。