Dennis
Dennis

Reputation: 441

Combining mayavi and matplotlib in the same figure

I will be making animations. In each frame I want to contain both a mayavi plot obtained with

mlab.pipeline.iso_surface(source, some other superfluous args)

and a matplotlib plot obtained using simply

pylab.plot(args)

I have scripts to do both separately, but have no idea how to go about combining them into one figure. I want the end product to be one script which contains the code from both the scripts that I currently have.

Upvotes: 3

Views: 3863

Answers (2)

DMTishler
DMTishler

Reputation: 509

Adding to the answer by DrV which helped me a great deal, you can work with the mlab figure to set resolution before screenshot such as with batch plotting:

mfig = mlab.figure(size=(1024, 1024))
src = mlab.pipeline.scalar_field(field_3d_numpy_array)
mlab.pipeline.iso_surface(src)
iso_surface_plot = mlab.screenshot(figure=mfig, mode='rgba', antialiased=True)
mlab.clf(mfig)
mlab.close()

# Then later in a matplotlib fig:
plt.imshow(iso_surface_plot)

Upvotes: 1

DrV
DrV

Reputation: 23540

AFAIK, there is no direct way because the backends used are so different. It does not seem possible to add matplotlib axes to mayavi.figure or vice versa.

However, there is a "kind of a way" by using the the mlab.screenshot.

import mayavi.mlab as mlab
import matplotlib.pyplot as plt

# create and capture a mlab object
mlab.test_plot3d()
img = mlab.screenshot()
mlab.close()

# create a pyplot
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax1.plot([0,1], [1,0], 'r')

# add the screen capture
ax2 = fig.add_subplot(122)
ax2.imshow(img)
ax2.set_axis_off()

enter image description here

This is not necessarily the nicest possible way of doing things, and you may bump into resolution problems, as well (check the size of the mayavi window). However, it gets the job done in most cases.

Upvotes: 4

Related Questions