向 Mapbox 添加图层时的问题(新)

问题描述 投票:0回答:1

此处重复问题:https://community.plotly.com/t/sudden-issues-when-adding-layers-to-mapbox/83115

一段时间(2年多)运行良好的代码突然开始抛出错误的情节。我已经测试了环境,这似乎是plotly/plotly.js 方面的问题——而不是环境影响。

情节== 5.17 (我已经将plotly升级到最新版本,但问题仍然存在。plotly对应的plotly.js的最新版本是2.30.0,而不是2.30.1,就其价值而言)。

该代码采用经纬对和相应数据的表,并以 MultiPolygons 的形式创建一组等高线,然后将所述等高线分层在地图框上。

图#1 是轮廓应该是什么样的。

图片 #2-4 是当前结果,通过绘图,显示图层未正确渲染。

尝试复制错误的数据可以在这里找到:https://github.com/jkiefn1/MiscData

import pandas as pd
from datetime import datetime, date
import plotly.express as px
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata,RectSphereBivariateSpline,Rbf
import geojsoncontour
import json
import branca
import scipy as sp
import scipy.ndimage
from geojson import Feature, Polygon, dump
import geopandas as gpd
from urllib.request import urlopen
import shapely.geometry
from shapely.geometry import Point, Polygon, GeometryCollection, Polygon, mapping
from shapely.ops import unary_union
from shapely.validation import make_valid
import math

# Contours
con = [-10, -5, -2.5, -1, 0, 1, 2.5, 5, 15]

colors = ['#e6572b','#f28f38','#f2b138','#f2d338','#7eae79','#0a88ba','#0b5e9f','#0c3383','#6600FF']

data = []

df = pd.read_csv('path/to/csv/from/GitHib/data.csv')

df_cont = df.dropna().copy()

levels = con
unit = ''


vmin   = 0
vmax   = 1
cm     = branca.colormap.LinearColormap(colors, vmin=vmin, vmax=vmax).to_step(len(levels))


x_orig = (df_cont['Long'].values.tolist())
y_orig = (df_cont['Lat'].values.tolist())
z_orig = np.asarray(df_cont[month].values.tolist())


x_arr          = np.linspace(np.min(x_orig), np.max(x_orig), 1000)
y_arr          = np.linspace(np.min(y_orig), np.max(y_orig), 1000)
x_mesh, y_mesh = np.meshgrid(x_arr, y_arr)


xscale = df_cont['Long'].max() - df_cont['Long'].min()
yscale = df_cont['Lat'].max() - df_cont['Lat'].min()

scale = np.array([xscale, yscale])


z_mesh = griddata((x_orig, y_orig), z_orig, (x_mesh, y_mesh), method='linear')


sigma = [5, 5]
z_mesh = sp.ndimage.filters.gaussian_filter(z_mesh, sigma, mode='nearest')

# Create the contour
contourf = plt.contourf(x_mesh, y_mesh, z_mesh, levels, alpha=0.9, colors=colors, 
                        linestyles='none', vmin=vmin, vmax=vmax)

# Convert matplotlib contourf to geojson
geojson = geojsoncontour.contourf_to_geojson(
    contourf=contourf,
    min_angle_deg=3,
    ndigits=2,
    unit=unit,
    stroke_width=1,
    fill_opacity=0.3)

d = json.loads(geojson)
len_features=len(d['features'])
if not data:
    data.append(d)
else:
    for i in range(len(d['features'])):
         data[0]['features'].append(d['features'][i])
            
with open('path/to/any/directory/to/hold/created_geojson/temp_conditions_contour.geojson', 'w') as f:
    dump(geojson, f)

# reading in the geospatial data for the state and province boundaries
with open('path/to/the/data/from/GitHub/states_and_provinces.geojson') as f:
    states_and_provinces_json = json.load(f)

conditions_json = json.loads(geojson)

fig = px.density_mapbox(
                        df_cont,
                        lat='Lat',
                        lon='Long',
                        z=month,
                        hover_data={
                            'Code':True,
                            'Lat': True,  # remove from hover data
                            'Long': True,  # remove from hover data
                            month: True,
                        },

                        center=dict(lat=38, lon=-95), # L48 + Lower CAN
                        zoom=2.75, # L48 + Lower CAN
                        
#                         center=dict(lat=38, lon=-112), # NAM
#                         zoom=2.1, # NAM
                        
                        opacity = 0.4,
                        radius = 15,
                        mapbox_style='white-bg',
                        color_continuous_scale=['rgb(0,0,0)',
                                                'rgb(19,48,239)',
                                                'rgb(115,249,253)',
                                                'rgb(114,245,77)',
                                                'rgb(254,251,84)',
                                                'rgb(235,70,38)'],
                        range_color = [100000000, 1000000000]
                    )


# Conditions outlines
fig.update_layout(
    mapbox={
        'layers': [
            {
                'source': f,
                'line': {'width':5},
                'type':'line',
                'type':'fill',
                'color': f['properties']['fill'],
                'opacity': 1,
            }
            for f in conditions_json['features']
        ],
    }
)

# States outlines
fig.update_layout(
    mapbox={
        "layers": [
            {
                'source': g,
                'line': {"width":0.5},
                'type':"line",
                'color': 'black',
                'opacity': 1,
            }
            for g in states_and_provinces_json["features"]
        ],
    }
)

# Update the hover info and legend -- legend was replaced with image of legend
fig.update_layout(xaxis=dict(fixedrange=True),
                  yaxis=dict(fixedrange=True),

                  coloraxis_showscale=False,
)

# Update size
fig.update_layout(
    autosize=False,
    width=900,
    height=900)

fig.show()

根据评论进行编辑

Python版本:3.11

情节版本:

Name: plotly
Version: 5.17.0
Summary: An open-source, interactive data visualization library for Python
Home-page: https://plotly.com/python/
Author: Chris P
Author-email: [email protected]
License: MIT
Location: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages
Requires: packaging, tenacity
Required-by: dash

plotly mapbox geojson
1个回答
0
投票

在与 r 初学者反复讨论之后,我调查了兼容性问题的可能性,发现无论出于何种原因,plotly5.26 和 python3.11 都不能很好地运行。这可能是我一个人特有的问题,不确定。

无论哪种方式,使用 python3.9.1 和plotly 5.15运行上述OP代码都按预期工作。

这不是最好的解决方案,但仍然是一个解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.