如何更改现有轴的 matplotlib 子图投影? [英] How do I change matplotlib's subplot projection of an existing axis?

查看:48
本文介绍了如何更改现有轴的 matplotlib 子图投影?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个简单的函数,该函数采用一个子图实例 (matplotlib.axes._subplots.AxesSubplot) 并将其投影转换为另一个投影,例如,转换为 cartopy.crs.CRS 投影.

I'm trying to construct a simple function that takes a subplot instance (matplotlib.axes._subplots.AxesSubplot) and transforms its projection to another projection, for example, to one of the cartopy.crs.CRS projections.

这个想法看起来像这样

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

def make_ax_map(ax, projection=ccrs.PlateCarree()):
    # set ax projection to the specified projection
    ...
    # other fancy formatting
    ax2.coastlines()
    ...

# Create a grid of plots
fig, (ax1, ax2) = plt.subplots(ncols=2)
# the first subplot remains unchanged
ax1.plot(np.random.rand(10))
# the second one gets another projection
make_ax_map(ax2)

当然,我可以直接使用fig.add_subplot()函数:

Of course, I can just use fig.add_subplot() function:

fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(121)
ax1.plot(np.random.rand(10))

ax2 = fig.add_subplot(122,projection=ccrs.PlateCarree())
ax2.coastlines()

但我想知道是否有适当的 matplotlib 方法来更改子图轴投影 定义之后.不幸的是,阅读 matplotlib API 并没有帮助.

but I was wondering if there is a proper matplotlib method to change a subplot axis projection after it was defined. Reading matplotlib API didn't help unfortunately.

推荐答案

您不能更改现有轴的投影,原因如下.但是,解决您的潜在问题的方法很简单,只需使用 matplotlib 文档 此处.例如,如果您希望所有子图都具有 cartopy.crs.PlateCarree 投影,您可以这样做

You can't change the projection of an existing axes, the reason is given below. However the solution to your underlying problem is simply to use the subplot_kw argument to plt.subplots() described in the matplotlib documentation here. For example, if you wanted all your subplots to have the cartopy.crs.PlateCarree projection you could do

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

# Create a grid of plots
fig, (ax1, ax2) = plt.subplots(ncols=2, subplot_kw={'projection': ccrs.PlateCarree()})

关于实际问题,在创建轴集时指定投影决定了您获得的轴类,每个投影类型都不同.例如

Regarding the actual question, specifying a projection when you create an axes set determines the axes class you get, which is different for each projection type. For example

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

ax1 = plt.subplot(311)
ax2 = plt.subplot(312, projection='polar')
ax3 = plt.subplot(313, projection=ccrs.PlateCarree())

print(type(ax1))
print(type(ax2))
print(type(ax3))

此代码将打印以下内容

<class 'matplotlib.axes._subplots.AxesSubplot'>
<class 'matplotlib.axes._subplots.PolarAxesSubplot'>
<class 'cartopy.mpl.geoaxes.GeoAxesSubplot'>

注意每个轴实际上是不同类的实例.

Notice how each axes is actually an instance of a different class.

这篇关于如何更改现有轴的 matplotlib 子图投影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆