Matplotlib - 2 Figures in Subplot - 1 is Animation

2019-07-04 21:57发布

I have two figures that I would like to plot in a subplot:

fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

Assume that ax1 is going to be populated with an animation which adds points ( a scatter plot). Ax2 then bins these points to a meshgrid and displays the density.

Can I display the animation in subplot 1, and on completion add the density image to subplot2?

1条回答
混吃等死
2楼-- · 2019-07-04 22:29

This should be possible. Please take a look at the example. You may also check the previous question:

Simple animation of 2D coordinates using matplotlib and pyplot

Below is a sample implementation. The second plot is hidden until the first stops rendering:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def update_line(num, data, line, img):
    line.set_data(data[...,:num])
    if num == 24:
        img.set_visible(True)
    return line, img

fig1 = plt.figure()

data = np.random.rand(2, 25)
ax1=plt.subplot(211)
l, = plt.plot([], [], 'rx')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
ax2=plt.subplot(212)
nhist, xedges, yedges = np.histogram2d(data[0,:], data[1,:])
img = plt.imshow(nhist, aspect='auto', origin='lower')
img.set_visible(False)
line_ani = animation.FuncAnimation(fig1, update_line, 25, 
                                   fargs=(data, l, img),
                                   interval=50, blit=True)
line_ani.repeat = False
plt.show()
查看更多
登录 后发表回答