【问题标题】:Embed Mayavi into a class and show the figure on a Jupyter Notebook cell将 Mayavi 嵌入到类中并在 Jupyter Notebook 单元格上显示图形
【发布时间】:2021-04-11 14:06:47
【问题描述】:

我正在尝试将 Mayavi 与我在 Jupyter Notebook 中的工作流程集成。以下精简的代码示例可能看起来不必要的复杂,但这些是我不允许更改的限制。

Test 类用于将某些内容绘制成mlab 图形。 Wrapper 类实例化了Test 类,而wrapper_func() 函数向用户公开:它返回Wrapper 实例,并且在关键字参数show=True 时应显示mlab 图形。

注意:我不能更改 Wrapperwrapper_func。此外,Test 类应该实现 show() 方法。

from mayavi import mlab
mlab.init_notebook()
import numpy as np

class Test:
    def __init__(self):
        self.fig = mlab.figure()
        self._add_data()
        
    def _add_data(self):
        pi = np.pi
        cos = np.cos
        sin = np.sin
        dphi, dtheta = pi / 250.0, pi / 250.0
        [phi, theta] = np.mgrid[0:pi + dphi * 1.5:dphi,
                                0:2 * pi + dtheta * 1.5:dtheta]
        m0 = 4; m1 = 3; m2 = 2; m3 = 3
        m4 = 6; m5 = 2; m6 = 6; m7 = 4
        r = sin(m0 * phi) ** m1 + cos(m2 * phi) ** m3 + \
            sin(m4 * theta) ** m5 + cos(m6 * theta) ** m7
        x = r * sin(phi) * cos(theta)
        y = r * cos(phi)
        z = r * sin(phi) * sin(theta)
        mlab.mesh(x, y, z, figure=self.fig)
        
    def show(self):
        return self.fig

class Wrapper:
    def __init__(self):
        self.t = Test()
        
    def show(self):
        self.t.show()

def wrapper_func(show=True):
    w = Wrapper()
    if show:
        w.show()
    return w

然后,用户在 Jupyter Notebook 单元格中写入:

wrapper_func()

这应该在输出单元格中显示绘图。不幸的是,这个数字没有显示出来。

或者,用户可以执行以下操作:

w = wrapper_func(show=False)
w.show()

如何在输出单元格中显示图形?

【问题讨论】:

    标签: python jupyter mayavi mayavi.mlab


    【解决方案1】:

    在 Test 类中创建网格时,将其分配给

    self.surf=mlab.mesh( ... )
    

    return self.surf in show()

    在程序中用作:

    t=Test();
    t.show()
    
    from mayavi import mlab
    mlab.init_notebook()
    import numpy as np
    
    class Test:
        def __init__(self):
            self.fig = mlab.figure()
            self._add_data()
            
        def _add_data(self):
            pi = np.pi
            cos = np.cos
            sin = np.sin
            dphi, dtheta = pi / 250.0, pi / 250.0
            [phi, theta] = np.mgrid[0:pi + dphi * 1.5:dphi,
                                    0:2 * pi + dtheta * 1.5:dtheta]
            m0 = 4; m1 = 3; m2 = 2; m3 = 3
            m4 = 6; m5 = 2; m6 = 6; m7 = 4
            r = sin(m0 * phi) ** m1 + cos(m2 * phi) ** m3 + \
                sin(m4 * theta) ** m5 + cos(m6 * theta) ** m7
            x = r * sin(phi) * cos(theta)
            y = r * cos(phi)
            z = r * sin(phi) * sin(theta)
            self.surf = mlab.mesh(x, y, z, figure=self.fig)
            
        def show(self):
            return self.surf
    
    t=Test()
    t.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 2018-05-10
      • 2019-04-11
      • 2020-02-15
      • 1970-01-01
      相关资源
      最近更新 更多