pythonplotlychoropleth

Draw polygons with Plotly and Choropleth


I want to draw a high number of polygons with different colors.

Using add_shapes generates plots which are way to slow.

I suspect that using choropleth would work well enough. Currently, I have the following code:

import plotly.express as px

polygons = [[(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)],
            [(3, 3), (3, 4), (4, 4), (4, 3), (3, 3)],
            [(5, 5), (5, 6), (6, 6), (6, 5), (5, 5)],
            [(7, 7), (7, 8), (8, 8), (8, 7), (7, 7)]]

geojson = {'features': [], 'type': 'FeatureCollection'}
ids = []
for index, poly in enumerate(polygons):
    temp_dict = {
        'geometry': {
            'coordinates': [polygons[index].copy()],
            'type': 'Polygon'},
        'type': 'Feature',
        'id': index}
    geojson['features'].append(temp_dict)
    ids.append(index)

fig = px.choropleth(
        geojson=geojson,
        color=ids,
        locations=ids)
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()

It seems to work, but I'd like to remove the map in the background, since my polygons are not related to geographic locations. Is there a way to do it or to get an equivalent result?


Solution

  • Using choropleth polygons is a great idea, you just need one thing to get rid of the base map :

    fig.update_geos(visible=False)
    

    NB. fig.update_geos(...) is a shortcut for fig.update_layout(geo=dict(...)).

    @see also Python Figure Reference: layout.geo