You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

提取经纬度并基于Plotly/Folium制作地震数据交互式地图

问题修正与交互式地图实现方案

一、数据读取代码修正

你的代码核心问题是字典推导式逻辑错误:{keys:row[key] for key in keys}会把元组('Latitude','Longitude')当作字典的唯一键,循环时不断覆盖值,最终只保留最后一个字段的内容。修正后的读取代码如下:

import csv

filename = '/kaggle/input/significant-earthquake-dataset-1900-2023/Significant Earthquake Dataset 1900-2023.csv'
keys = ('Latitude','Longitude')
records = []

with open(filename,'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # 正确生成包含Latitude和Longitude的字典
        records.append({key: float(row[key]) for key in keys})

# 查看第一条数据,格式应为 {'Latitude': xxx, 'Longitude': xxx}
print(records[0])

二、用Plotly实现交互式地图可视化

Plotly的scatter_geo可以直接基于经纬度生成交互式地图,还能结合震级等属性做分层可视化:

完整代码示例

import csv
import plotly.express as px

filename = '/kaggle/input/significant-earthquake-dataset-1900-2023/Significant Earthquake Dataset 1900-2023.csv'

# 读取完整数据集(包含震级、地点、年份等字段)
data = []
with open(filename,'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        data.append({
            'Latitude': float(row['Latitude']),
            'Longitude': float(row['Longitude']),
            'Magnitude': float(row['Magnitude']),
            'Year': row['Year'],
            'Location': row['Location Name']
        })

# 生成交互式地图
fig = px.scatter_geo(
    data,
    lat='Latitude',
    lon='Longitude',
    color='Magnitude',  # 震级越高,标记颜色越深
    size='Magnitude',   # 震级越高,标记尺寸越大
    hover_name='Location',  # 鼠标悬停显示地震地点
    hover_data=['Year', 'Magnitude'],  # 悬停展示年份和震级
    projection='natural earth',  # 采用自然地球投影
    title='1900-2023年全球重大地震分布'
)

# 调整布局,去除多余边距
fig.update_layout(height=600, margin={"r":0,"t":50,"l":0,"b":0})
fig.show()

三、用Folium实现交互式地图

如果需要生成可嵌入网页的Leaflet地图,用Folium更合适:

完整代码示例

import csv
import folium

filename = '/kaggle/input/significant-earthquake-dataset-1900-2023/Significant Earthquake Dataset 1900-2023.csv'

# 初始化地图,中心设为全球中心点,初始缩放级别2
m = folium.Map(location=[0, 0], zoom_start=2)

# 读取数据并添加地图标记
with open(filename,'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        lat = float(row['Latitude'])
        lon = float(row['Longitude'])
        mag = float(row['Magnitude'])
        location = row['Location Name']
        year = row['Year']
        
        # 配置弹出窗口内容
        popup_content = f"""
        <strong>地点:</strong> {location}<br>
        <strong>年份:</strong> {year}<br>
        <strong>震级:</strong> {mag}
        """
        # 根据震级设置标记颜色
        color = 'red' if mag >= 7 else 'orange' if mag >= 6 else 'blue'
        
        # 添加圆形标记
        folium.CircleMarker(
            location=[lat, lon],
            radius=mag/2,  # 震级与标记尺寸成正比
            color=color,
            fill=True,
            fill_color=color,
            popup=folium.Popup(popup_content, max_width=300)
        ).add_to(m)

# 将地图保存为HTML文件,可直接在浏览器打开
m.save('earthquake_map.html')

四、基于GeoJSON的Plotly可视化

如果需要先将CSV转成GeoJSON格式再可视化,可按以下步骤实现:

转换GeoJSON并可视化的代码

import csv
import json
import plotly.express as px

filename = '/kaggle/input/significant-earthquake-dataset-1900-2023/Significant Earthquake Dataset 1900-2023.csv'
geojson_data = {
    "type": "FeatureCollection",
    "features": []
}

# 读取CSV并转换为GeoJSON格式
with open(filename,'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        feature = {
            "type": "Feature",
            "properties": {
                "Magnitude": float(row['Magnitude']),
                "Year": row['Year'],
                "Location": row['Location Name']
            },
            "geometry": {
                "type": "Point",
                "coordinates": [float(row['Longitude']), float(row['Latitude'])]
            }
        }
        geojson_data['features'].append(feature)

# 用Plotly加载GeoJSON并生成地图
fig = px.choropleth_mapbox(
    geojson=geojson_data,
    locations=[f"feat_{i}" for i in range(len(geojson_data['features']))],
    featureidkey="properties.Location",
    color=[f['properties']['Magnitude'] for f in geojson_data['features']],
    mapbox_style="carto-positron",
    zoom=1,
    center={"lat": 0, "lon": 0},
    hover_data=["Year", "Magnitude"],
    title='1900-2023年全球重大地震分布(GeoJSON)'
)

fig.update_layout(margin={"r":0,"t":50,"l":0,"b":0})
fig.show()

内容的提问来源于stack exchange,提问作者Ido Kobi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 11:05:18