如何验证地震可视化Python代码正确性?求更优数据处理方案
震级数据异常处理与代码验证方案
一、验证代码正确性的方法
- 统计数据量变化:打印原始震级列表和过滤后列表的长度,确认负数震级被正常过滤
print(f"原始震级数量: {len(mags)}") print(f"过滤后震级数量: {len(clean_mags)}") - 排查异常样本:找出所有负数震级对应的地震条目,确认是否为真实异常数据
negative_mag_items = [eq for eq in all_eq_dicts if eq["properties"]["mag"] < 0] print(f"负数震级条目数量: {len(negative_mag_items)}") # 打印第一条负数震级的完整信息 if negative_mag_items: print(json.dumps(negative_mag_items[0], indent=2)) - 断言验证过滤结果:强制确保过滤后的震级列表中无负数
assert all(mag >= 0 for mag in clean_mags), "过滤后仍存在负数震级" - 可视化校验:在hover文本中明确显示震级数值,查看生成的地图中是否存在负数标记(若有则说明过滤逻辑未生效)
二、更优的震级数据处理方案
你当前代码的核心问题是:仅过滤了震级列表,但未同步过滤对应的经纬度、hover文本等数据,导致Plotly绘图时marker.size的长度与lon/lat不匹配,这才是引发ValueError的根本原因。直接在遍历数据时同步过滤异常项,能从根源避免此类问题,同时还能处理震级为None的情况:
修改后的完整代码
import json from plotly.graph_objs import Scattergeo, Layout from plotly import offline # 加载JSON数据 filename = 'earthquake_data/seven_days_earthquake.json' with open(filename, encoding='utf-8') as f: eq_data = json.load(f) # 生成可读JSON文件(可选) readable_file = 'earthquake_data/readable_eq_data.json' with open(readable_file, 'w') as f: json.dump(eq_data, f, indent=4) # 提取数据并同步过滤异常项 title = eq_data["metadata"]["title"] all_eq_dicts = eq_data["features"] mags, lons, lats, hover_texts = [], [], [], [] for eq_dict in all_eq_dicts: mag = eq_dict["properties"]["mag"] # 过滤条件:震级不为空且非负数 if mag is not None and 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"]) # 绘制地震地图 data = [{ 'type': 'scattergeo', 'lon': lons, 'lat': lats, 'text': hover_texts, 'marker': { 'size': [5*mag for mag in mags], 'color': mags, 'colorscale': 'Ylorrd', 'reversescale': True, 'colorbar': {'title': 'Magnitude'}, }, }] my_layout = Layout(title=title) fig = {'data': data, 'layout': my_layout} offline.plot(fig, filename='sevenday_quakes.html')
方案优势
- 数据一致性:所有相关列表(震级、经纬度、hover文本)同步过滤,彻底避免长度不匹配导致的绘图错误
- 更全面的异常处理:同时处理震级为
None的情况(地震数据中可能存在无震级记录的条目) - 代码更简洁:无需额外的过滤循环,一步完成数据提取与清洗
关于try/except无效的说明
你之前尝试的try/except未生效,大概率是因为错误并非来自震级本身的数值转换,而是来自Plotly绘图时的列表长度不匹配。此时即使捕获异常也无法解决根本问题,从源头保证数据一致性才是最优解。
内容的提问来源于stack exchange,提问作者Alonskii
相关产品推荐
相关产品推荐

