Search code examples
python-3.xjupyter-notebookdata-sciencematplotlib-basemapmap-projections

MPL Basemap Projections not showing output properly


So I have this old code from my teacher that plots a Mollweide Projection using Basemap

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap

from itertools import chain

def draw_map(m, scale=0.2):
  # draw a shaded-relief image
  im1 = m.shadedrelief(scale=scale)
  # print(im1, vars(im1))
  # print(f'{dir(im1) = }')
  # lats and longs are returned as a dictionary
  lats = m.drawparallels(np.linspace(-90, 90, 13))
  lons = m.drawmeridians(np.linspace(-180, 180, 13))
  # keys contain the plt.Line2D instances
  lat_lines = chain(*(tup[1][0] for tup in lats.items()))
  lon_lines = chain(*(tup[1][0] for tup in lons.items()))
  all_lines = chain(lat_lines, lon_lines)
  # cycle through these lines and set the desired style
  for line in all_lines:
    line.set(linestyle='-', alpha=0.3, color='w')


fig = plt.figure(figsize=(8, 6), edgecolor='w')
m = Basemap(projection='moll', resolution=None,
            lat_0=0, lon_0=0)

draw_map(m)

And when I'm trying to plot it I got this blank output without the Earth background Image:

Actual Output Image

Expected Output:

Expected Output

As far as I've searched, I can't find the solution for this problem

And this issue happens for every Geographical Projection methods in Basemap like bluemarble , shadedrelief as far as I saw

And I'm running this code in VS Code's Jupyter Notebook, with Python v3.11.0

And I also got the same output in Google Colab, with mpltoolkits and basemap installed

And same output even if I ran it in a separate Python file


Solution

  • Nevermind, It's a simple fix

    I just have to add these 2 lines in the draw_map function to update it like this:

    from itertools import chain
    
    def draw_map(m, scale=0.2):
      # draw a shaded-relief image
    
      # These 2 lines
      im1 = m.shadedrelief(scale=scale) # Value stored in a variable to resolve a bug
      im1.axes.add_image(im1) # The line that resolves the "No BG Image" bug
    
      # lats and longs are returned as a dictionary
      lats = m.drawparallels(np.linspace(-90, 90, 13))
      lons = m.drawmeridians(np.linspace(-180, 180, 13))
      # keys contain the plt.Line2D instances
      lat_lines = chain(*(tup[1][0] for tup in lats.items()))
      lon_lines = chain(*(tup[1][0] for tup in lons.items()))
      all_lines = chain(lat_lines, lon_lines)
      # cycle through these lines and set the desired style
      for line in all_lines:
        line.set(linestyle='-', alpha=0.3, color='w')
    

    Output:

    Output Image