内容来自中国大学MOOC,北京理工大学,python数据分析与展示课程,侵删。
如有错误,烦请指出。
(1) 建立从 HasTraits 继承的类
(2) 显示窗口
'''实例1:建立简单的Mayavi窗口'''
from numpy import sqrt, sin, mgrid
from traits.api import HasTraits, Instance
from traitsui.api import View, Item
from tvtk.pyface.scene_editor import SceneEditor
from mayavi.tools.mlab_scene_model import MlabSceneModel
from mayavi.core.ui.mayavi_scene import MayaviScene
# 建立HasTraits的继承类
class ActorViewer(HasTraits):
# 建立场景scene
scene = Instance(MlabSceneModel, ())
# 建立视图view
view = View(Item(name='scene',
editor=SceneEditor(scene_class=MayaviScene),
show_label=False,
resizable=True,
height=500,
width=500),
resizable=True)
# 初始化函数
def __init__(self, **traits):
HasTraits.__init__(self, **traits)
self.generate_data()
# 生成数据
def generate_data(self):
# 建立数据
X, Y = mgrid[-2:2:100j, -2:2:100j]
R = 10 * sqrt(X**2+Y**2)
Z = sin(R)/R
# 可视化数据
self.scene.mlab.surf(X, Y, Z, colormap='cool')
# 显示窗口
a = ActorViewer()
a.configure_traits()
(1) 建立从 HasTraits 继承的类
(2) 显示窗口
'''实例2:基于交互控制的 Mayavi 窗口'''
from traits.api import HasTraits, Range, Instance, on_trait_change
from traitsui.api import View, Item, Group
from mayavi.core.api import PipelineBase
from mayavi.core.ui.api import MayaviScene, SceneEditor, MlabSceneModel
from numpy import arange, pi, cos, sin
dphi = pi/300.
phi = arange(0.0, 2*pi + 0.5*dphi, dphi, 'd')
# 建立数据
def curve(n_mer, n_long):
mu = phi*n_mer
x = cos(mu) * (1+cos(n_long*mu/n_mer)*0.5)
y = sin(mu) * (1+cos(n_long*mu/n_mer)*0.5)
z = 0.5 * sin(n_long*mu/n_mer)
t = sin(mu)
return x, y, z, t
# 建立HasTraits的继承类
class MyModel(HasTraits):
# 定义窗口中的变量n_meridional和n_longitudinal
n_meridional = Range(0, 30, 6) # 滑动条控件
n_longitudinal = Range(0, 30, 11) # 华东条控件
# 建立场景scene
scene = Instance(MlabSceneModel, ())
# 建立管线plot
plot = Instance(PipelineBase)
# 建立监听函数update_plot
@on_trait_change('n_meridional,n_longitudinal,scene.activated')
def update_plot(self):
# 调用curve()生成数据
x, y, z, t = curve(self.n_meridional, self.n_longitudinal)
#如果plot未绘制则生成plot3d
if self.plot is None:
self.plot = self.scene.mlab.plot3d(x, y, z, t,
tube_radius=0.025, colormap='Spectral')
#如果数据有变化,将数据更新即重新赋值
else:
self.plot.mlab_source.set(x=x, y=y, z=z, scalars=t)
# 建立视图view
view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene),
height=250, width=300, show_label=False),
Group('_', 'n_meridional', 'n_longitudinal'),
resizable=True)
# 显示窗口
model = MyModel()
model.configure_traits()