当我尝试使用 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()
.
是列名中的特殊字符,表示嵌套。您可以重命名列名称以将 .
替换为例如_
,或使用 \
: 转义特殊字符
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')
)