如何修复Scattergeo Marker Size属性的ValueError错误?
问题描述
运行地震数据可视化代码时,执行'size': [5*mag for mag in mags]行触发ValueError,提示scattergeo.marker的size属性收到无效负数元素(如-0.35、-1.0等)。尝试用Try/Except语句未解决。
错误信息:
ValueError:
Invalid element(s) received for the 'size' property of scattergeo.marker
Invalid elements include: [-0.35000000000000003, -1.0, -0.8500000000000001, -0.1, -2.5,
-0.05, -2.8000000000000003, -2.75, -3.35, -0.4]
原代码:
import json from plotly.graph_objs import Scattergeo, Layout from plotly import offline # Get a JSON file. filename = 'earthquake_data/seven_days_earthquake.json' with open(filename, encoding='utf-8') as f: eq_data = json.load(f) # Create a readable file from the loaded json file above. readable_file = 'earthquake_data/readable_eq_data.json' with open(readable_file, 'w') as f: json.dump(eq_data, f, indent=4) # Exploring the structure of the data. title = eq_data["metadata"]["title"] all_eq_dicts = eq_data["features"] mags, lons, lats, hover_texts = [], [], [], [] for eq_dict in all_eq_dicts: try: mags.append(eq_dict["properties"]["mag"]) lons.append(eq_dict["geometry"]["coordinates"][0]) lats.append(eq_dict["geometry"]["coordinates"][1]) hover_texts.append(eq_dict["properties"]["title"]) except ValueError: print("Data not available.") # Map the earthquakes. data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, # Outline marks in the map. 'marker': { 'size': [5*mag for mag in mags], 'color': mags, 'colorscale': 'Viridis', 'reversescale': True, 'colorbar': {'title': 'Magnitude'}, }, }] # One-week Earthquake data output. my_layout = Layout(title = f'{title}') fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='sevenday_quakes.html')
修复方案
- 过滤负震级数据:震级为负数属于无效或异常记录,可在收集数据阶段直接排除,保证后续计算的size均为有效值:
for eq_dict in all_eq_dicts: try: mag = eq_dict["properties"]["mag"] # 仅保留震级≥0的数据 if mag >= 0: mags.append(mag) lons.append(eq_dict["geometry"]["coordinates"][0]) lats.append(eq_dict["geometry"]["coordinates"][1]) hover_texts.append(eq_dict["properties"]["title"]) else: print(f"Skipping negative magnitude: {mag}") except Exception as e: print(f"Data not available: {e}") - 修正size计算逻辑:若不想过滤数据,可在生成size列表时将负数转为最小有效正数(避免marker不可见):
# 方案1:取震级绝对值计算size 'size': [5*abs(mag) for mag in mags] # 方案2:设置最小size为1,同时保留正震级的比例关系 'size': [max(5*mag, 1) if mag >=0 else 1 for mag in mags] - 调整异常捕获逻辑:原代码的Try/Except仅捕获
ValueError,但负震级数据不会触发该异常,需主动判断震级有效性,而非依赖异常捕获。
内容的提问来源于stack exchange,提问作者Alonskii
相关产品推荐
相关产品推荐

