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

使用Altair绘制USGS地震数据图表出现空白问题求助

用Altair绘制USGS地震数据直方图出现空白图问题

我尝试用Altair绘制USGS地震数据的震级分布直方图时,始终得到空白图表,但检查DataFrame后确认properties.mag列确实存在。唯一成功绘制的是用经纬度生成的图表。

我的代码如下:

current_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')

api_url = "https://earthquake.usgs.gov/fdsnws/event/1/query"
parameters = {
    'format': 'geojson',  
    'starttime': '2023-01-01',  
    'endtime': current_time,  
    'minmagnitude': 4.5  
}

response = requests.get(api_url, params=parameters)
data = response.json()

earthquakes = data['features']

df = pd.json_normalize(earthquakes)
df['longitude'] = df['geometry.coordinates'].apply(lambda x: x[0])
df['latitude'] = df['geometry.coordinates'].apply(lambda x: x[1])
df['depth'] = df['geometry.coordinates'].apply(lambda x: x[2])
df['country'] = df['properties.place'].apply(lambda x: x.split(',')[-1].strip())

import altair as alt
alt.data_transformers.disable_max_rows()

hist_mag = alt.Chart(df).mark_bar().encode(
    x=alt.X('properties.mag:Q', bin = True, title='Magnitude'),
    y=alt.Y('count()', title='Number of Earthquakes')
).properties(title='Distribution of Earthquake Magnitudes')

hist_mag.display()

排查和解决方法

  • 清理无效数据:先检查properties.mag列是否存在空值或非数值类型,执行以下代码过滤:
    # 查看空值数量
    print(df['properties.mag'].isna().sum())
    # 过滤空值
    df = df.dropna(subset=['properties.mag'])
    
  • 手动指定分箱范围:默认分箱可能超出数据实际范围,手动设置分箱参数匹配震级区间:
    x=alt.X('properties.mag:Q', bin=alt.Bin(extent=[4.5, 10], step=0.5), title='Magnitude')
    
  • 验证数据分布:打印数据的统计信息,确认震级数值范围是否合理:
    print(df['properties.mag'].describe())
    
  • 更换显示方式:如果display()方法无效,直接在Jupyter单元格中输入hist_mag,或者先启用默认渲染器:
    alt.renderers.enable('default')
    hist_mag
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 06:02:54