When I tried to draw the graph of USGS earthquakes using Altair, it always gives me blank graph. Here are my codes
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()
But when I check the dataframe, the column still exists and I do not know how to fix it. This is the screenshot of the code drawing the graph
code and this is the graph I got graph
The only successful example is when I use latitude and longitude.latitude graph
It happens because .
is a special character in column names, indicating nesting. You can either rename the column names to replace .
with e.g. _
, or escape the special character by prefixing it with in a raw string:
alt.Chart(df, title='Distribution of Earthquake Magnitudes').mark_bar().encode(
x=alt.X(r'properties.mag:Q').bin().title('Magnitude'),
y=alt.Y('count()').title('Number of Earthquakes')
)
0