Search code examples
pythonmatplotlibvisualizationmayavi

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.


Solution

  • 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.