如何提高 ipython 交互对 matplotlib 3D 绘图的响应能力



Python 2.7.9, matplotlib 1.4.0, ipython 2.3.1, MacBook Pro Retina

我正在将 ipython 的 interact() 与 ipython 笔记本中的 3D 绘图一起使用,但发现在更改滑块控件时图形更新太慢。下面是运行时出现此问题的示例代码:

from IPython.html.widgets import *
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
%matplotlib inline
def plt3Dsin(angle):
    npnts = 100
    rotationangle_radians = math.radians(angle)
    tab_x = np.linspace(0,3,npnts)
    tab_y = np.zeros(npnts)
    tab_z = np.sin(2.0*np.pi*tab_x)
    yrotate = tab_z * np.sin(rotationangle_radians)
    zrotate = tab_z * np.cos(rotationangle_radians)
    fig = plt.figure()
    ax = Axes3D(fig)
    ax.plot(tab_x, yrotate, zrotate)
    ax.set_xlim3d([0.0,3.0])
    ax.set_ylim3d([-1.0,1.0])
    ax.set_zlim3d([-1.0,1.0])
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
interact(plt3Dsin,angle=(0,360,5));

我试图在下面的代码中将图形和轴的创建与实际绘图分开,但是第一次更改滑块时,图形不会更新,第二次更改时,图形完全消失。我想我做错了什么,但一直无法弄清楚是什么。(下面的全局变量的使用只是这个简单示例代码的快速权宜之计。

npnts = 100
tab_x = np.linspace(0,3,npnts)
def init_plt3Dsin():
    global fig
    global ax
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot([], [], [], lw=2)
    ax.set_xlim3d([0.0,3.0])
    ax.set_ylim3d([-1.0,1.0])
    ax.set_zlim3d([-1.0,1.0])
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')
def plt3Dsin(angle):
    global fig
    global ax
    rotationangle_radians = math.radians(angle)
    tab_y = np.zeros(npnts)
    tab_z = np.sin(2.0*np.pi*tab_x)
    yrotate = tab_z * np.sin(rotationangle_radians)
    zrotate = tab_z * np.cos(rotationangle_radians)
    ax.plot(tab_x, yrotate, zrotate)
init_plt3Dsin()
interact(plt3Dsin,angle=(0,360,5));

> Tcaswell的评论建议使用nbagg后端提供了一个很好的方法来解决我的问题,因为它使第一个代码块运行得足够快,令人满意。

最新更新