Matplotlib / Cartopy-Jupyter笔记本中使用FuncAnimation的动画空白

问题描述 投票:0回答:1

我使用IPython Display模块使用了相同的动画,但是我希望它具有交互性,所以我尝试使用matplotlib动画模块。如果我用%matplotlib notebook运行以下命令,它将仅返回一个空白屏幕。如果使用%matplotlib inline运行它,则仅返回第一帧。如果我以内联模式运行,并使用IPython.dispay中的HTML模块将其另存为HTML5视频,则该视频将显示空白屏幕的视频,而在其下方则显示最后一帧(而非第一帧)。

下面是代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import colors
from matplotlib import animation
import random

import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

fname = r'D:\Downloads\gadm36_USA_shp\gadm36_USA_2.shp'

fig = plt.figure()
ax = plt.axes((-82.65, 27.65, 0.595, 0.5), projection=ccrs.PlateCarree())
shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), edgecolor='black')
ax.add_feature(shape_feature, alpha=0.5)

ax.set_extent([-82.65,-82.055,27.65,28.15])

cmap = colors.ListedColormap(['0000', 'green', 'yellow', 'orange', 'red'])
bounds = [0, .25, .5, .75, .9, 1]
norm = colors.BoundaryNorm(bounds, cmap.N)
pdf = plt.imshow(np.zeros((20,20)), cmap=cmap, extent=(-82.65,-82.055,27.65,28.15))

def search():
    ...
    yield [op, norm]
    ...

def plot_search(args):
    op = args[0]
    updated_norm = args[1]

    new_z = op.reshape((20,20))

    pdf.set_norm(updated_norm)
    pdf.set_data(new_z)
    return [pdf]
ani = animation.FuncAnimation(fig, plot_search, frames=search, blit=True)
plt.plot()

search()是生成器函数。即使我用list(search())包装它,也仍然无法使用。

我是matplotlib / cartopy的新手,因此非常感谢您的帮助!

python matplotlib jupyter-notebook cartopy
1个回答
1
投票

您在调用axes时的定义有点奇怪。我认为当您使用笔记本时,它会通过使用“紧”边界框来保存,这意味着它会自动调整图像的大小以适合绘图上的内容-在您的情况下,它会使图像变大。在笔记本之外使用时,默认图像不适合您定义的轴。以下对我有用:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import colors
from matplotlib import animation
import random

import cartopy.crs as ccrs
from cartopy.io.shapereader import Reader
from cartopy.feature import ShapelyFeature

#fname = r'D:\Downloads\gadm36_USA_shp\gadm36_USA_2.shp'

fig = plt.figure()
ax = plt.axes(projection=ccrs.PlateCarree())
#shape_feature = ShapelyFeature(Reader(fname).geometries(), ccrs.PlateCarree(), edgecolor='black')
#ax.add_feature(shape_feature, alpha=0.5)

ax.set_extent([-82.65,-82.055,27.65,28.15])

cmap = colors.ListedColormap(['0000', 'green', 'yellow', 'orange', 'red'])
bounds = [0, .25, .5, .75, .9, 1]
norm = colors.BoundaryNorm(bounds, cmap.N)
pdf = plt.imshow(np.zeros((20,20)), cmap=cmap, extent=(-82.65,-82.055,27.65,28.15))

def search():
    yield np.random.randn(400), plt.Normalize(-1, 1)

def plot_search(args):
    op, updated_norm = args

    new_z = op.reshape((20,20))

    pdf.set_norm(updated_norm)
    pdf.set_data(new_z)
    return [pdf]
ani = animation.FuncAnimation(fig, plot_search, frames=search, blit=True)
plt.show()

如果您手动创建轴,也可以看到this example参数的外观。

© www.soinside.com 2019 - 2024. All rights reserved.