Plotly地震地图绘制遇负震级报错:如何过滤负数值?
解决Plotly绘制地震地图时负震级导致的size属性错误
我用Plotly绘制近期地震数据地图,想根据震级设置点的大小,但数据里有负震级记录,运行代码时报错:
The 'size' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
我添加了if mag > 0的过滤条件但并未生效,代码如下:
import json from plotly.graph_objs import Scattergeo, Layout from plotly import offline from plotly import colors # explore the structure of the data filename = "data/all_month.geojson" with open(filename) as f: all_eq_data = json.load(f) all_eq_dicts = all_eq_data["features"] title = all_eq_data["metadata"]["title"] mags, lons, lats, hover_texts = [], [], [], [], for eq_dict in all_eq_dicts: if mag > 0: mags.append(eq_dict["properties"]["mag"]) lons.append(eq_dict["geometry"]["coordinates"] [1]) lats.append(eq_dict["geometry"]["coordinates"] [0]) hover_texts.append(eq_dict["properties"]["title"]) # Map the earthquakes data = [{ "type": "scattergeo", "lon": lons, "lat": lats, "text": hover_texts, "marker": { "size": [5*mag for mag in mags], "color": mags, "colorscale": "Viridis", "reversescale": True, "colorbar": {"title": "Magnitude"}, }, }] my_layout = Layout(title=title) fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="global_month_earthquakes_2023.html")
问题原因
你写的if mag > 0中的mag变量未提前定义,循环里还没获取当前地震的震级就做判断,导致这个条件完全没起到过滤作用,负震级数据仍被加入列表,最终传给Plotly的size属性包含负值,触发错误。
修正方案
先从当前eq_dict中取出震级,再做非负判断,同时处理震级为None的情况(避免类型错误)。修正后的代码:
import json from plotly.graph_objs import Scattergeo, Layout from plotly import offline from plotly import colors # explore the structure of the data filename = "data/all_month.geojson" with open(filename) as f: all_eq_data = json.load(f) all_eq_dicts = all_eq_data["features"] title = all_eq_data["metadata"]["title"] 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"][1]) lats.append(eq_dict["geometry"]["coordinates"][0]) hover_texts.append(eq_dict["properties"]["title"]) # Map the earthquakes data = [{ "type": "scattergeo", "lon": lons, "lat": lats, "text": hover_texts, "marker": { "size": [5*mag for mag in mags], "color": mags, "colorscale": "Viridis", "reversescale": True, "colorbar": {"title": "Magnitude"}, }, }] my_layout = Layout(title=title) fig = {"data": data, "layout": my_layout} offline.plot(fig, filename="global_month_earthquakes_2023.html")
额外优化提示
如果不想完全过滤负震级数据,可将负震级转为0(Plotly接受0作为size值),修改判断部分为:
mag = eq_dict["properties"]["mag"] # 处理空值并将负震级转为0 if mag is None: continue mag = max(mag, 0) mags.append(mag) # 后续lons、lats、hover_texts的append代码保留
内容的提问来源于stack exchange,提问作者bavver23
相关产品推荐
相关产品推荐

