Hi. I’m trying to write a US Counties shape (population and color added) file into a Plotly choropleth.
The US counties shape file is from: http://www2.census.gov/geo/tiger/GENZ2016/shp/cb_2016_us_county_5m.zip
The first record of the geopandas dataframe (created from the above) looks like the below. I added color, and population.
STATEFP 04
COUNTYFP 015
COUNTYNS 00025445
AFFGEOID 0500000US04015
GEOID 04015
NAME Mohave
LSAD 06
ALAND 34475567011
AWATER 387344307
geometry POLYGON ((-114.755618 36.087166, -114.753638 3...
FIPS_COMBINED 04015
CountyPop_2016 205249.000
Pop_norm 0.020
Color #fffad7
Name: 1, dtype: object
I’m getting strange errors when I try to plot it… I’m new to Plotly so any help is appreciated…
I’m using http://andrewfulton.io/programming/2016/10/01/county-choropleth-colorbar.html as an example.
The code I’m using is this…
layers_ls = []
for x in cdf.index:
item_dict = dict(sourcetype = 'geojson',
source = cdf.iloc[x]['geometry'],
type = 'fill',
color = cdf.iloc[x]['Color'])
layers_ls.append(item_dict)
colorscl = [[i * .01, v] for i,v in enumerate(colors)]
data = go.Data([
go.Scattermapbox(
lat = [0],
lon = [0],
marker = go.Marker(
cmax=100,
cmin=0,
colorscale = colorscl,
showscale = True,
autocolorscale=False,
color=range(0,101),
colorbar= go.ColorBar(
len = .89
)
),
mode = 'markers')
])
layout = go.Layout(
title = 'US Population Density',
height=1050,
width=800,
autosize=True,
hovermode='closest',
mapbox=dict(
layers= layers_ls,
accesstoken=mapbox_access_token,
bearing=0,
center=dict(
lat=39.03,
lon=-105.7
),
pitch=0,
zoom=5.5,
style='light'
),
)
fig = dict(data = data, layout=layout)
py.iplot(fig, filename='US_Pop_Density.jpg')
In the above code, the layer_ls dictionary looks like this
layers_ls[0]
{‘color’: ‘#fffad7’,
‘source’: <shapely.geometry.polygon.Polygon at 0x7f6b8273d128>,
‘sourcetype’: ‘geojson’,
‘type’: ‘fill’}
This is the error I’m getting
TypeError Traceback (most recent call last)
<ipython-input-7-81bc2bd14875> in <module>()
37
38 fig = dict(data = data, layout=layout)
---> 39 py.iplot(fig, filename='US_Pop_Density.jpg')
~/anaconda3/envs/OSMNX/lib/python3.6/site-packages/plotly/plotly/plotly.py in iplot(figure_or_data, **plot_options)
133 if 'auto_open' not in plot_options:
134 plot_options['auto_open'] = False
--> 135 url = plot(figure_or_data, **plot_options)
136
137 if isinstance(figure_or_data, dict):
~/anaconda3/envs/OSMNX/lib/python3.6/site-packages/plotly/plotly/plotly.py in plot(figure_or_data, validate, **plot_options)
226 data = fig.get('data', [])
227 plot_options['layout'] = fig.get('layout', {})
--> 228 response = v1.clientresp(data, **plot_options)
229
230 # Check if the url needs a secret key
~/anaconda3/envs/OSMNX/lib/python3.6/site-packages/plotly/api/v1/clientresp.py in clientresp(data, **kwargs)
27 payload = {
28 'platform': 'python', 'version': version.__version__,
---> 29 'args': _json.dumps(data, **dumps_kwargs),
30 'un': creds['username'], 'key': creds['api_key'], 'origin': 'plot',
31 'kwargs': _json.dumps(kwargs, **dumps_kwargs)
~/anaconda3/envs/OSMNX/lib/python3.6/json/__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
236 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
237 separators=separators, default=default, sort_keys=sort_keys,
--> 238 **kw).encode(obj)
239
240
~/anaconda3/envs/OSMNX/lib/python3.6/site-packages/plotly/utils.py in encode(self, o)
134
135 # this will raise errors in a normal-expected way
--> 136 encoded_o = super(PlotlyJSONEncoder, self).encode(o)
137
138 # now:
~/anaconda3/envs/OSMNX/lib/python3.6/json/encoder.py in encode(self, o)
197 # exceptions aren't as detailed. The list call should be roughly
198 # equivalent to the PySequence_Fast that ''.join() would do.
--> 199 chunks = self.iterencode(o, _one_shot=True)
200 if not isinstance(chunks, (list, tuple)):
201 chunks = list(chunks)
~/anaconda3/envs/OSMNX/lib/python3.6/json/encoder.py in iterencode(self, o, _one_shot)
255 self.key_separator, self.item_separator, self.sort_keys,
256 self.skipkeys, _one_shot)
--> 257 return _iterencode(o, 0)
258
259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
~/anaconda3/envs/OSMNX/lib/python3.6/site-packages/plotly/utils.py in default(self, obj)
202 except NotEncodable:
203 pass
--> 204 return _json.JSONEncoder.default(self, obj)
205
206 @staticmethod
~/anaconda3/envs/OSMNX/lib/python3.6/json/encoder.py in default(self, o)
178 """
179 raise TypeError("Object of type '%s' is not JSON serializable" %
--> 180 o.__class__.__name__)
181
182 def encode(self, o):
TypeError: Object of type 'range' is not JSON serializable
Any help is appreciated. Wish writing counties into Plotly was as easy as States :\