PyVista子图中同一网格设置不同标量及更新标量的问题
PyVista多子图网格标量绘制与更新问题解决
问题1:同一网格复用导致子图共享色阶
- 现象:将同一个网格对象用于多个子图绘制不同标量时,子图会共享色阶(示例中图1、图2);重新创建网格对象则恢复正常(图1、图3)。
- 原因:PyVista的标量数据存储在网格对象本身,复用同一网格时,后续设置的标量会覆盖之前的数据,导致所有使用该网格的子图共享同一组标量与色阶。
- 解决方法:调用
add_mesh时指定copy_mesh=True,为每个子图创建独立的网格副本,避免数据共享。
问题2:子图标量更新仅最后一个子图生效
- 现象:调用
update_scalars时默认仅更新最后添加的网格;切换子图后直接调用仍无法更新对应子图的标量。 - 原因:
update_scalars的默认逻辑是操作最后添加到绘图器的网格对象,与当前选中的子图无关;若未保存各子图网格的引用,无法指定更新目标。 - 解决方法:保存每个子图添加的网格对象引用,更新时通过
mesh参数明确指定要更新的目标网格,无需依赖子图切换。
update_scalars函数说明(官方注释翻译)
def update_scalars(self, scalars, mesh=None, render=True): mesh : vtk.PolyData 或 vtk.UnstructuredGrid,可选 已添加到绘图器的对象。如果为None,则使用最后添加的网格。
修正后的完整示例代码
import pyvista as pv from pyvistaqt import BackgroundPlotter shape = (3, 1) plotter = BackgroundPlotter(shape=shape) # 子图1:使用copy_mesh创建独立副本并保存网格引用 plotter.subplot(0, 0) sphere = pv.Sphere() mesh1 = plotter.add_mesh(sphere, scalars=10*sphere.points[:, 2], scalar_bar_args={'title':'V1'}, copy_mesh=True) # 子图2:同样使用copy_mesh plotter.subplot(1, 0) mesh2 = plotter.add_mesh(sphere, scalars=sphere.points[:, 2], scalar_bar_args={'title':'V2'}, copy_mesh=True) # 子图3:新创建网格(或用copy_mesh) plotter.subplot(2, 0) sphere3 = pv.Sphere() mesh3 = plotter.add_mesh(sphere3, scalars=sphere3.points[:, 2], scalar_bar_args={'title':'V3'}) # 更新子图1的标量 plotter.update_scalars(sphere.points[:,2]*5, mesh=mesh1) # 更新子图2的标量 plotter.update_scalars(sphere.points[:,2]*8, mesh=mesh2) # 更新子图3的标量 plotter.update_scalars(sphere3.points[:,2]*3, mesh=mesh3) plotter.show()
内容的提问来源于stack exchange,提问作者WCCC
相关产品推荐
相关产品推荐

