如何更改现有轴的matplotlib子块投影?

2024-10-01 07:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试构造一个简单的函数,它接受一个子块实例(matplotlib.axes._subplots.AxesSubplot),并将其投影转换为另一个投影,例如,转换为一个cartopy.crs.CRS投影。

这个主意看起来像这样

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()函数:

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 API没有帮助。


Tags: the函数addmatplotlibfigpltax投影
2条回答

在回答这个问题之后:

In python, how can I inherit and override a method on a class instance, assigning this new version to the same name as the old one?

我找到了一种方法,在创建斧头后更改它的投影,至少在下面的简单示例中是可行的,但是我不知道这个解决方案是否是最好的方法

from matplotlib.axes import Axes
from matplotlib.projections import register_projection

class CustomAxe(Axes):
    name = 'customaxe'

    def plotko(self, x):
        self.plot(x, 'ko')
        self.set_title('CustomAxe')

register_projection(CustomAxe)


if __name__ == '__main__':
    import matplotlib.pyplot as plt

    fig = plt.figure()

    ## use this syntax to create a customaxe directly
    # ax = fig.add_subplot(111, projection="customaxe")

    ## change the projection after creation
    ax = plt.gca()
    ax.__class__ = CustomAxe

    ax.plotko(range(10))    
    plt.show()

无法更改现有轴的投影,原因如下。但是,解决底层问题的方法只是使用matplotlib文档here中描述的subplot_kw参数。例如,如果希望所有子块都具有cartopy.crs.PlateCarree投影,则可以执行

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()})

关于实际问题,在创建轴集时指定投影将确定获得的轴类,每个投影类型的轴类不同。例如

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'>

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

相关问题 更多 >