matplotlib 如何在gridspec中使用Cartopy

ybzsozfc  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(141)

我想创建一个图,左边是Cartopy图,右边是两个堆叠的Matplotlib图。如果我只使用Matplotlib图,代码如下。

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
gs = gridspec.GridSpec(2, 2)

# LEFT
ax = fig.add_subplot(gs[:, 0])
ax.plot(np.arange(0, 1000, 100))

# RIGHT TOP
ax = fig.add_subplot(gs[0, 1])
ax.plot(np.arange(0, 1000, 100))

# RIGHT BOTTOM
ax = fig.add_subplot(gs[1, 1])
ax.plot(np.arange(0, 1000, 100))

plt.show()

到目前为止一切顺利
但是,如果我添加一个Cartopy图,我不能使它保持在左侧的轴上。我想我如何使用ax = plt.axes()有问题。

import cartopy.crs as ccrs
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
gs = gridspec.GridSpec(2, 2)

# LEFT
ax = fig.add_subplot(gs[:, 0])

ax = plt.axes(
    projection = ccrs.Orthographic(
        central_longitude=0,
        central_latitude=0
        )
    )

ax.stock_img()

# RIGHT TOP
ax = fig.add_subplot(gs[0, 1])
ax.plot(np.arange(0, 1000, 100))

# RIGHT BOTTOM
ax = fig.add_subplot(gs[1, 1])
ax.plot(np.arange(0, 1000, 100))

plt.show()

如何使Cartopy图与左侧子图的轴保持一致?

umuewwlo

umuewwlo1#

这是因为在创建左窗格后,您为cartopy创建了一个覆盖整个图的新轴。相反,您需要在fig.add_subplot内部传递projection,如下所示:

import cartopy.crs as ccrs
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
gs = gridspec.GridSpec(2, 2)

# LEFT
ax = fig.add_subplot(gs[:, 0], projection = ccrs.Orthographic(
        central_longitude=0,
        central_latitude=0
        ))

ax.stock_img()

# RIGHT TOP
ax = fig.add_subplot(gs[0, 1])
ax.plot(np.arange(0, 1000, 100))

# RIGHT BOTTOM
ax = fig.add_subplot(gs[1, 1])
ax.plot(np.arange(0, 1000, 100))

plt.show()

相关问题