Plotly:在地图上绘制点和线时自动房间in/out到合适的区域

Plotly: auto room in/out to the suitable region when plotting points and lines on the map

自动调整显示正确地图范围的正确方法是什么:

这是当前的显示,我几乎看不到绘图的真实部分:

理想显示:

下面是代码。

import plotly.graph_objects as go
import plotly.io as pio
import plotly

lon1 = [113.076843,113.154191,113.737213,113.842405,114.244183]
lat1 = [23.10993,23.218533,23.047626,22.987975,22.601581]

lon2 = [113.364738, 113.664108,113.661705,114.244183]
lat2 = [22.997112,22.878038,22.869216,22.601581]

lon_trip1 = lon1
lat_trip1 = lat1

lon_trip2 = lon2
lat_trip2 = lat2

fig = go.Figure()
fig.add_trace(go.Scattermapbox(
        mode="markers+lines",
        lon=lon_trip1,
        lat=lat_trip1,
        name="trip1",
        marker={'size': 10}))
fig.add_trace(go.Scattermapbox(
        mode="markers+lines",
        lon=lon_trip2,
        lat=lat_trip2,
        name="trip2",
        marker={'size': 10}))

fig.update_layout(
        margin={'l': 113, 't': 24, 'b': 22, 'r': 115},
            autosize=True,
        mapbox={
            # 'center': {'lon': 10, 'lat': 10},
            # 'autosize'=True,
            'style': "stamen-terrain",
            # 'center': {'lon': -20, 'lat': -20},
            # 'zoom': 1
        })

pio.write_image(fig,'C:/Users/user/Desktop/test.png',width=1980, height=1080)
plotly.offline.plot(fig, filename='C:/Users/user/Desktop/plot' + '.html')
fig.show()

要在使用地图框时自动设置中心位置,您需要一个特殊的方法。我已经使用 official reference 中的示例修改了您的代码。中心经纬度设置不当,请指正。

import plotly.graph_objects as go
import plotly.io as pio 
import plotly

lon1 = [113.076843, 113.154191, 113.737213, 113.842405, 114.244183 ]
lat1 = [23.10993, 23.218533, 23.047626, 22.987975, 22.601581 ]

lon2 = [113.364738, 113.664108, 113.661705,114.244183]
lat2 = [22.997112, 22.878038, 22.869216, 22.601581 ]

lon_trip1 = lon1
lat_trip1 = lat1

lon_trip2 = lon2
lat_trip2 = lat2

fig = go.Figure()
fig.add_trace(go.Scattermapbox(
    mode="markers+lines",
    lon=lon_trip1,
    lat=lat_trip1,
    name="trip1", marker={'size': 10}))

fig.add_trace(
    go.Scattermapbox(
        mode="markers+lines",
        lon=lon_trip2,
        lat=lat_trip2,
        name="trip2",
        marker={'size': 10}))

fig.update_layout(
    margin={'l': 113, 't': 24, 'b': 22, 'r': 115},
    mapbox=dict(style='carto-positron',
                center=go.layout.mapbox.Center(lon=113.664, lat=22.878),
                pitch=0,
                zoom=8)
)

fig.add_annotation(x=lat2[0],
                   xref='x',
                   y=lon2[0],
                   yref='y',
                   text="DAZHEN'GANG",
                   font=dict(color='blue', size=20))

pio.write_image(fig,'./data/plotly_choropleth.png',width=1980, height=1080)
#plotly.offline.plot(fig, filename='C:/Users/user/Desktop/plot' + '.html')
fig.show()