For people having a hard time creating a layer from a shapefile (.shp) and plotting it over a Choroplethmapbox chart, here’s one successful way of doing it:
1 - Install geopandas (This can be tricky, it’s easier if you use Anaconda, otherwise you have to install some components manually with pip - python - how to successfully install pyproj and geopandas? - Stack Overflow). geopandas is helpful to read a shapefile as a pandas DataFrame.
2 - read your shapefile into a Pandas DataFrame:
import geopandas as gpd
geodf = gpd.read_file('path_to_shp_file')
3 - Create a GeoJSON file and read it:
geodf.to_file("path_to_GeoJSON _file", driver = "GeoJSON")
with open("path_to_GeoJSON _file") as geofile:
j_file = json.load(geofile)
So now you have successfully converted a shapefile into an appropriate format (GeoJSON) for plotly to read.
4 - IMPORTANT - When creating the plot You’ll need to have a feature-id associated with each feature, so you can associate the GeoJSON-formatted geometry with the z attribute (Mapbox Choropleth Maps | Python | Plotly). If you did not have an id in the first place, you can add it, since this j_file is basically a big dict (there’s probably a better way of doing this though):
i=1
for feature in j_file["features"]:
feature ['id'] = str(i).zfill(2)
i += 1
5 - Just follow the example instructions (Mapbox Choropleth Maps | Python | Plotly) and add data indexed by the same ‘id’ as the j_file. the locations attribute of the Choroplethmapbox
chart should be a list (or a column of a pandas DataFrame) with the same values as the the ‘id’ key values in the j_file. The z attribute should have the values in the same order.