笔记本中的 Altair 图表

问题描述 投票:0回答:1

当我尝试使用 Altair 绘制 USGS 地震图时,它总是给我空白图。这是我的代码

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()

但是当我检查数据框时,该列仍然存在,我不知道如何修复它。这是绘制图表的代码的屏幕截图 code这是我得到的图表graph

唯一成功的例子是当我使用纬度和经度时。latitude graph

python visualization altair
1个回答
0
投票

发生这种情况是因为

.
是列名中的特殊字符,表示嵌套。您可以重命名列名称以将
.
替换为例如
_
,或使用
\
:

转义特殊字符
alt.Chart(df, title='Distribution of Earthquake Magnitudes').mark_bar().encode(
    x=alt.X('properties\\.mag:Q').bin().title('Magnitude'),
    y=alt.Y('count()').title('Number of Earthquakes')
)

© www.soinside.com 2019 - 2024. All rights reserved.