Search code examples
pythonjsonplotly

How do I know if the code below is correct?


From my previous request, I created an empty list (clean_mag) and then loop through the mags list, and append the positive numbers to the clean_mag(list) because I realized that the negative numbers was the reason why I was getting a ValueError in my previous code. Although the code worked, but I would like to know if is correct, but as a self-learner, I do not know how else to cross check my code for validity.
How do I know that I am not missing anything out? I would like to know if there's a better way to go through the mag list, and then work with the positive numbers without allowing the negative numbers to blow up the code. I thought about using try/except but it didn't work.

import json
from plotly.graph_objs import Scattergeo, Layout
from plotly import offline


# Get a JSON file.
filename = 'earthquake_data/seven_days_earthquake.json'
with open(filename, encoding='utf-8') as f:
    eq_data = json.load(f)

# Create a readable file from the loaded json file above.

readable_file = 'earthquake_data/readable_eq_data.json'
with open(readable_file, 'w') as f:
    json.dump(eq_data, f, indent=4)

# Exploring the structure of the data.
title = eq_data["metadata"]["title"]
all_eq_dicts = eq_data["features"]

mags, lons,  = [], []
lats, hover_texts = [], []

for eq_dict in all_eq_dicts:
    mags.append(eq_dict["properties"]["mag"])
    lons.append(eq_dict["geometry"]["coordinates"][0])
    lats.append(eq_dict["geometry"]["coordinates"][1])
    hover_texts.append(eq_dict["properties"]["title"])

clean_mags = []

for item in mags:
    if item < 0:
        pass
    else:
        clean_mags.append(item)

# Map the earthquakes.
data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    'text': hover_texts,

    # Outline marks in the map
    'marker': {
        'size':[5*mag for mag in clean_mags],
        'color': mags,
        'colorscale': 'Ylorrd',
        'reversescale': True,
        'colorbar': {'title': 'Magnitude'},
    },

}]

# One-week Earthquake data output.
my_layout = Layout(title = f'{title}')
fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='sevenday_quakes.html')

Solution

  • Since you did not present any data, I got similar data from here. If the magnitude is greater than or equal to 0, the latitude, longitude, and name will also be listed. This answer may differ from the data the questioner has, and the method of answering may not be valid. If this is the case, please comment.

    from urllib import request
    import json
    
    url='https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson'
    with request.urlopen(url) as f:
        eq_data = json.load(f)
    
    
    # Exploring the structure of the data.
    title = eq_data["metadata"]["title"]
    all_eq_dicts = eq_data["features"]
    
    mags, lons,  = [], []
    lats, hover_texts = [], []
    
    for eq_dict in all_eq_dicts:
        mag = eq_dict["properties"]["mag"]
        if mag > 0:
            mags.append(eq_dict["properties"]["mag"])
            lons.append(eq_dict["geometry"]["coordinates"][0])
            lats.append(eq_dict["geometry"]["coordinates"][1])
            hover_texts.append(eq_dict["properties"]["title"])
    
    import plotly.graph_objs as go
    
    fig = go.Figure()
    
    fig.add_trace(go.Scattergeo(
        lon=lons,
        lat=lats,
        text=hover_texts,
        marker=dict(
            size=[x*3 for x in mags],
            color=mags,
            colorscale='Ylorrd',
            reversescale=False,
            colorbar=dict(title='Magnitude'),
        )
    ))
    
    fig.update_layout(
        autosize=True,
        height=600,
        title_text='All Earthquakes(Last 7 days)',
        showlegend=False,
        geo = dict(
                landcolor='rgb(217, 217, 217)',
            )
        )
    
    fig.show()
    

    enter image description here