python - 具有固定 Z 限制的 Matplotlib 动画 3D 条形图

标签 python animation matplotlib

以下代码有效,除了一行;如果我包括 ax.set_zlim3d(minz, maxz) (第 29 行)然后条形图都在 x-y 平面上偏移。如何更改此代码以修复 z 轴的限制而不发生这种情况?

%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import proj3d
# need to install ffmpeg, on osx; brew install ffmpeg
from matplotlib import cm, animation, rc
rc('animation', html='html5')
#from IPython.display import HTML
import itertools

def setup_plot(minz, maxz):
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    xypos = [(3,3),(2,3),(1,3),(3,2),(2,2),(1,2),(3,1),(2,1),(1,1)]
    xpos = [i for i,j in xypos]
    ypos = [j for i,j in xypos]
    zpos = [0,0,0,0,0,0,0,0,0]
    dx = 0.5 * np.ones_like(zpos)
    dy = 0.5 * np.ones_like(zpos)
    values = np.zeros(9)

    poly3d = ax.bar3d(xpos, ypos, zpos, dx, dy, values, zsort='average')

    ax.view_init(elev=35,azim=45)
    ax.zaxis.set_rotate_label(False)  # disable automatic rotation
    ax.set_zlabel('Potential (V)', rotation=90)
    ax.set_zlim3d(minz, maxz)

    showxy=False
    if showxy:
        ax.set_xlabel('x')
        ax.set_ylabel('y')
    else:
        ax.set_xticks([])
        ax.set_yticks([])

    ax.grid(True)

    sm = plt.cm.ScalarMappable(cmap=cm.jet)
    sm.set_array([minz, maxz])
    fig.colorbar(sm, shrink=0.5, aspect=5)

    fig.set_figwidth(8)
    fig.set_figheight(6)

    return fig, ax

minz, maxz = 0.5, 1.5
fig, ax = setup_plot(minz, maxz)

def update_bars(i, iter_vals, minz, maxz):
    xypos = [(3,3),(2,3),(1,3),(3,2),(2,2),(1,2),(3,1),(2,1),(1,1)]
    xpos = [i for i,j in xypos]
    ypos = [j for i,j in xypos]
    zpos = [0,0,0,0,0,0,0,0,0]
    dx = 0.5 * np.ones_like(zpos)
    dy = 0.5 * np.ones_like(zpos)

    values = iter_vals.next()

    values_norm = values - minz
    colors = cm.jet(values_norm)

    ax.collections.pop()
    ax.bar3d(xpos, ypos, zpos, dx, dy, values, color=colors, zsort='average')

    return

values = np.random.random((20,9))*1.5

anim = animation.FuncAnimation(fig, update_bars, frames=values.shape[0], interval=600, blit=False, 
                               fargs=[itertools.cycle(values), minz, maxz], repeat=True)

anim

最佳答案

当您更改 z 轴上的限制时,您会移动绘图并实质上放大条形,将中心移动到 x-y 平面上的 (3.25,3.25)。您可以通过在 setup_plot 函数中插入以下行来手动更改 x-y 平面的限制:

ax.set_ylim3d(2,4.5)
ax.set_xlim3d(2,4.5)

关于python - 具有固定 Z 限制的 Matplotlib 动画 3D 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668967/

相关文章:

ios - 具有执行功能和 UI 更新的重复动画

python - 使用 QPropertyAnimation 进行线条动画

ios - 创建 Iphone MapKit 显示用户位置环动画

python - 轴标签的 Matplotlib DateFormatter 不起作用

Python 变长泛型类型

python - Pytest 覆盖范围 : run cov over multiple folders

Python 日志模块不遵守低于 '30' 的 setLevel(警告)?

C#中默认的Python等价物

python - 使用 pylab 绘制文件中的特定列和行

python - 对于 matplotlib 子图,Axes.invert_axis() 不适用于 sharey=True