Change the background colour of a projected Matplotlib axis

给你一囗甜甜゛ 提交于 2019-12-24 03:48:24

问题


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: Removing the projection=ccrs.Mercator() argument from the above code produces this expected result:

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)

回答1:


Cartopy is still not very well-rounded in terms of controlling some things, and I'm afraid you need to dig into the code to find some things out.

I think the basic tweak you need is this :

ax2.background_patch.set_fill(False)

My hacked example :

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

fig = plt.figure()
ax1 = fig.add_subplot(111, axisbg='b')
ax2 = fig.add_subplot(111, axisbg='None', projection=ccrs.Mercator())
ax2.background_patch.set_fill(False)
ax2.add_feature(cartopy.feature.LAND)
ax2.coastlines(color='red', linewidth=0.75)
plt.show()

Picture :

Edit: removed copy/paste error

HTH
Patrick




回答2:


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, -180, 180])

ax.add_feature(LAND)
ax.coastlines()

plt.show()



来源:https://stackoverflow.com/questions/32200438/change-the-background-colour-of-a-projected-matplotlib-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!