matplotlib python中3d绘图动画镜头的去重

kkih6yb8  于 2023-01-26  发布在  Python
关注(0)|答案(3)|浏览(203)

我正在用python导出一个动画,但是图例重复出现。我只有一个情节,希望动画的每一帧都有一个图例项。这是我的脚本:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
x = np.linspace(0., 10., 100)
y = np.linspace(0., 10., 100)
z = np.random.rand(100)
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot (111, projection="3d")

def init():
    # Plot the surface.
    ax.scatter3D(x, y, z, label='random', s=10)
    ax.set_zlabel('Z [m]')
    ax.set_ylabel('Y [m]')
    ax.set_xlabel('X [m]')
    plt.legend()
    ax.grid(None)
    return fig,

def animate(i):
    ax.view_init(elev=20, azim=i)
    return fig,

# Animate
ani = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=360, interval=200, blit=True)

# Export
ani.save('random data.gif', writer='pillow', fps=30, dpi=50)

这是一个动画,其中的图例重复了三次:

我非常感谢你的帮助。

k5ifujac

k5ifujac1#

问题是init被多次调用,您应该避免在此函数中创建图形。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

x = np.linspace(0., 10., 100)
y = np.linspace(0., 10., 100)
z = np.random.rand(100)
fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot (111, projection="3d")

# Plot the surface.
ax.scatter3D(x, y, z, label='random', s=10)
ax.set_zlabel('Z [m]')
ax.set_ylabel('Y [m]')
ax.set_xlabel('X [m]')
plt.legend()
ax.grid(None)

def init():
    return fig,

def animate(i):
    ax.view_init(elev=20, azim=i)
    return fig,

# Animate
ani = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=360, interval=200, blit=True)

# Export
ani.save('random data.gif', writer='pillow', fps=30, dpi=50)

输出:

vjrehmav

vjrehmav2#

按照here的建议,将plt.legend()替换为以下3行:

def init():
    # Plot the surface.
    ax.scatter3D(x, y, z, label='not random', s=10)
    ax.set_zlabel('Z [m]')
    ax.set_ylabel('Y [m]')
    ax.set_xlabel('X [m]')

    # REPLACE plt.legend() STARTS HERE
    handles, labels = plt.gca().get_legend_handles_labels()
    by_label = dict(zip(labels, handles))
    plt.legend(by_label.values(), by_label.keys())
    # REPLACE plt.legend() ENDS HERE    

    ax.grid(None)
    return fig,

bmp9r5qi

bmp9r5qi3#

嗯,这算不上什么答案,但我不能发表评论,还是想分享一下这个信息:
我运行了你的脚本,它对我来说很好:

我使用的是水蟒环境,这是我用来运行脚本的环境:

相关问题