Matplotlib:在同一窗口中绘制一系列图形。

5
我正在测试一个算法,我希望使用matplotlib生成一系列显示中间结果的图形。我不需要动画,也不需要在屏幕上显示多个图形或子图。我只想生成一系列图形(可能使用pyplot),完成后显示单个窗口。然后,我想使用箭头在图形序列中导航。如何做到这样呢?我尝试搜索,但只能找到subplot或在屏幕上显示多个图形。谢谢。

有几种不同的方法,哪种最好取决于你正在做什么。不同的图形在每个图中是否具有相同的绘图类型?(例如,您是绘制线条,然后是图像,还是只是具有不同数据的线条)每个图中的项目数量是否不同?(例如,每个图中是否有3条具有不同数据的线条,或者线条数量是否不同?)适用于任何内容的方法也是最慢的。 - Joe Kington
1
这些图都是同一类型的:我在二维平面上绘制点和线。 - AkiRoss
1个回答

11

最常见的方法是在同一图中创建一个轴序列,每次只显示一个。

以下是一个示例(使用左右箭头键控制显示哪个绘图):

import matplotlib.pyplot as plt
import numpy as np

def main():
    x = np.linspace(0, 10, 100)
    axes = AxesSequence()
    for i, ax in zip(range(3), axes):
        ax.plot(x, np.sin(i * x))
        ax.set_title('Line {}'.format(i))
    for i, ax in zip(range(5), axes):
        ax.imshow(np.random.random((10,10)))
        ax.set_title('Image {}'.format(i))
    axes.show()

class AxesSequence(object):
    """Creates a series of axes in a figure where only one is displayed at any
    given time. Which plot is displayed is controlled by the arrow keys."""
    def __init__(self):
        self.fig = plt.figure()
        self.axes = []
        self._i = 0 # Currently displayed axes index
        self._n = 0 # Last created axes index
        self.fig.canvas.mpl_connect('key_press_event', self.on_keypress)

    def __iter__(self):
        while True:
            yield self.new()

    def new(self):
        # The label needs to be specified so that a new axes will be created
        # instead of "add_axes" just returning the original one.
        ax = self.fig.add_axes([0.15, 0.1, 0.8, 0.8], 
                               visible=False, label=self._n)
        self._n += 1
        self.axes.append(ax)
        return ax

    def on_keypress(self, event):
        if event.key == 'right':
            self.next_plot()
        elif event.key == 'left':
            self.prev_plot()
        else:
            return
        self.fig.canvas.draw()

    def next_plot(self):
        if self._i < len(self.axes):
            self.axes[self._i].set_visible(False)
            self.axes[self._i+1].set_visible(True)
            self._i += 1

    def prev_plot(self):
        if self._i > 0:
            self.axes[self._i].set_visible(False)
            self.axes[self._i-1].set_visible(True)
            self._i -= 1

    def show(self):
        self.axes[0].set_visible(True)
        plt.show()

if __name__ == '__main__':
    main()

如果它们都是相同类型的图表,你可以只更新涉及到的艺术家的数据。如果每个图表中的项数相同,这尤其容易。我暂时不提供示例,但如果上面的示例占用内存过多,则仅更新艺术家的数据将更轻便。


谢谢!我正好在寻找这样的东西! - AkiRoss

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接