Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the background colour of a projected Matplotlib axis

I'm trying to create a figure using Cartopy that requires a projected axis to be drawn over an unprojected axis.

Here is a simple as possible version of the code that substitutes content on the axes for background colour:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs

#Setup figure
fig = plt.figure()

#Unprojected axis
ax1 = fig.add_subplot(111, axisbg='b')

#Projected axis
ax2 = fig.add_subplot(111, axisbg='None', projection=ccrs.Mercator())

plt.show()

Which instead of leaving the blue axis visible produces this: enter image description here Removing the projection=ccrs.Mercator() argument from the above code produces this expected result: enter image description here

How do I make the projected axis background transparent?

Thanks!

Edit: I've tried these other methods of setting the background transparent with no luck:

ax2 = fig.add_subplot(111, axisbg='None', alpha=0, projection=ccrs.Mercator())
ax2.patch.set_facecolor('none')
ax2.patch.set_alpha(0)
like image 878
Siyh Avatar asked Sep 13 '25 11:09

Siyh


1 Answers

You can use imshow() to project an image onto the background of your map. Cartopy uses the stock_img() method for this purpose.

You can also get a solid background colour, by creating a 2x2 pixel image with NumPy, and projecting it over the entire map extents:

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.feature import LAND
    
ax = plt.axes(projection=ccrs.PlateCarree())

# Set RGB value to ocean colour
ax.imshow(np.tile(np.array([[[200, 200, 255]]], 
          dtype=np.uint8), [2, 2, 1]),
      origin='upper',
      transform=ccrs.PlateCarree(),
      extent=[-180, 180, -90, 90])

ax.add_feature(LAND)
ax.coastlines()

plt.show()

enter image description here

like image 160
onewhaleid Avatar answered Sep 16 '25 00:09

onewhaleid