Search code examples
pythonplotlygoogle-colaboratorygeopandaschoropleth

Plotly choropleth map not showing in Google Colab


I have been trying every single solution that has been suggested over the Internet, but none of them seems to work for me. I get either a blank page or just the legend/colorbar for my choropleth map when I try to plot with Plotly in Colab. Can someone help me out with it? Here is a very basic code that I try to plot.

import plotly.express as px
fig = px.choropleth(gdf,
                    locations="id",
                    geojson=geojson,
                    color="Total - Visible minority",
                    scope="north america",
                    projection="conic conformal"
                    )
fig.show()

Solution

  • I've encountered a couple of errors, with suggestions you may have seen:

    Plotly notebook mode with google colaboratory

    In particular these three possible fixes:

    fig.show(renderer="colab")
    

    Or by setting global default:

    import plotly.io as pi
    pio.renderers.default = "colab"
    

    Finally, and unfortunately the possibility of having to set browser defaults in each cell by creating this function:

      def configure_plotly_browser_state():
          import IPython
          display(IPython.core.display.HTML('''
                <script src="/static/components/requirejs/require.js"></script>
                <script>
                  requirejs.config({
                    paths: {
                      base: '/static/base',
                      plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
                    },
                  });
                </script>
                '''))
    

    And then running configure_plotly_browser_state() in the cell with fig.show()

    Not a beautiful solution I know, but hopefully they work for you.