Search code examples
pythonplotlytypeerror

How can I handle a TypeError?


I'm just getting acquainted with Plotly. I tried to make a different size for every marker on the plot depending on the value of the magnitude and this happened:

 'size': [5*mag for mag in mags],
             ~^~~~
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

Also, I get a ValueError when setting a color:

ValueError: 
    Invalid element(s) received for the 'color' property of scattergeo.marker
        Invalid elements include: [None]

If I get it right, Python doesn't recognize the values in the mags list as numbers. The full code is below:

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

filename = "past_30.geojson"

with open(filename, encoding='utf-8') as f:
    all_eq_data = json.load(f)

readable_file_1 = 'readable_eq_data.json'
with open(readable_file_1, 'w') as f:
    json.dump(all_eq_data, f, indent=4)

all_eq_dicts = all_eq_data['features']
mags, lons, lats = [], [], []


for eq_dict in all_eq_dicts:
    mag = eq_dict['properties']['mag']
    lon = eq_dict['geometry']['coordinates'][0]
    lat = eq_dict['geometry']['coordinates'][1]

    mags.append(mag)
    lons.append(lon)
    lats.append(lat)


data = [{
    'type': 'scattergeo',
    'lon': lons,
    'lat': lats,
    'marker': {
        'size': [5*mag for mag in mags],
        'color': mags,
        'colorscale': 'Viridis', 
        'reversescale': True,
        'colorbar': {'title': 'Magnitude'},
        },
}]

my_layout = Layout(title='Global Earthquakes')

fig = {'data': data, 'layout': my_layout}
offline.plot(fig, filename='glob_eq.html')

I tried to fix this problem by putting int() and float() but in both ways it ended up as another TypeError:

mag = int(mag)
          ^^^^^^^^
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'

I checked the mags list itself ( print(mags)) and I believe it contains float numbers:

[2.07, 2.07, 2.2, 3.3, 1.91, 1.89, 1.6, 1.76...]

I had similar problems while working with functions, but putting return in the end fixed the issue every time.

Am I missing something?


Solution

  • The error messages indicate that mags contains None. You can verify this by checking that the statement None in mags returns True.

    You need to somehow fill the None values in mags. Depending on your use case, you can pick a default value as suggested in the comments or impute the mean, median, or some other individual value. You could also remove the None values from the mags array, but this would require you to adjust the length of the other arrays you are passing to your data dictionary.