为什么在for循环之外定义plt.figure()?

时间:2018-06-28 12:08:50

标签: python matplotlib

在以下代码中,为什么我必须在for循环开始时定义figax?当我在循环末尾编写它时,它只给我一个图形,而不给两个。

fig = plt.figure()
ax = fig.add_subplot(111)
Ls = [2, 4]
for L in range(len(Ls)):
    x = np.arange(10)
    y = np.random.randint(0, 11, size=10)
    print(y)
    ax.plot(x,y)
    ax.set_label("x")
    ax.set_label("y")
    plt.savefig("jj.png")
    plt.show()

2 个答案:

答案 0 :(得分:1)

考虑将图形定义为获取一张纸以进行绘制。因此,如果要在同一图中绘制多个图,则需要定义一次(在循环之前)并在其上绘制多个图(在循环中)。为此,您需要将savefig()show从循环主体中移出:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

Ls = [2, 4]
for L in range(len(Ls)):
    x = np.arange(10)
    y = np.random.randint(0, 11, size=10)
    print(y)
    ax.plot(x,y)
    ax.set_label("x")
    ax.set_label("y")

plt.savefig("jj.png")
plt.show()

哪个会给你这样的东西

enter image description here

如果需要两个图,则可以使用subplots()方法创建多个轴,然后可以在其上调用plot(),如下所示:

import matplotlib.pyplot as plt
import numpy as np

fig, axes = plt.subplots(2, 1) # This creates two axes objects, one for the upper one for the lower plot
for ax in axes:
    x = np.arange(10)
    y = np.random.randint(0, 11, size=10)
    ax.plot(x,y)
    ax.set_xlabel("x")
    ax.set_ylabel("y")

fig.tight_layout()
plt.savefig("jj.png")
plt.show()

这会给你这样的东西:

enter image description here

答案 1 :(得分:0)

您的for循环有两个步骤。

如果在循环内创建from plot_graph import func_plot from unittest.mock import patch # unittest boilerplate... @patch('matplotlib.pyplot.figure') def test_func_plot(self, mock_fig): # whatever tests I want... mock_fig.assert_called() # some assertion on the mock object ,将有两个图,每个迭代一个;如果将fig = plt.figure()放置在for循环之外,则fig = plt.figure()将绘制在创建的唯一图形中。

plt.plot(...)在for循环之外时,仍然有两个图但一个图,但是由于行plt.figure(),一个图替换了另一个图或在另一个图上绘制了图。

如果删除行plt.show(),您将在同一图中看到两个图。