如何在Python中为一个变量赋值并在多图中使用该变量。

问题描述 投票:0回答:1

我想用一个函数来创建一个情节。一旦我有了绘图,我想在多图中使用它。

例如,我可以创建以下函数。

def fig_1(x):
    # create a new figure
    fig = plt.figure()
    plt.plot([1*x, 2*x, 3*x, 4*x])
    return fig

然后我想用这样的函数:

subplot(3,2,1) = fig_1(1)
subplot(3,2,2) = fig_1(2)
subplot(3,2,3) = fig_1(3)
subplot(3,2,4) = fig_1(4)
subplot(3,2,5) = fig_1(5)
subplot(3,2,6) = fig_1(6)

为了绘制最终的情节。

from pylab import *
pdf = matplotlib.backends.backend_pdf.PdfPages("Cal8010.pdf")
for fig in xrange(1,figure().number): 

这样一来,就不能用了。我可以做我的想法吗?

感谢任何形式的帮助

python function matplotlib subplot figure
1个回答
0
投票

首先:我创建了子图,并在每个子图中创建了一个情节。

import matplotlib.pyplot as plt
import numpy as np


def fig_1(ax, x, y):
    ax.plot(x, y)


fig, ax = plt.subplots(3, 2)

for i in range(3):
    for j in range(2):
        x = np.random.random(10)
        y = np.random.random(10)
        fig_1(ax[i, j], x, y)
        ax[i, j].set_title(f"Subplot #{2*i + j + 1}")

plt.show()

现在,你也可以绘制一个空的数组 并进一步更新数据到这个图上。

import matplotlib.pyplot as plt
import numpy as np


def fig_1(ax):
    line, = ax.plot([], [])
    return line


fig, ax = plt.subplots(3, 2)

lines = []
for i in range(3):
    for j in range(2):
        x = np.random.random(10)
        y = np.random.random(10)
        lines.append((fig_1(ax[i, j]), x, y))
        ax[i, j].set_title(f"Subplot #{2*i + j + 1}")        

for p in lines:
    l, x, y = p
    l.set_xdata(x)
    l.set_ydata(y)


fig.canvas.draw()
fig.canvas.flush_events()

plt.show()

但这可能会很棘手,因为每个图上的两个轴都不适应数据,所以图可能会出界(所以你可能需要将x和y的限制固定为数据的最小和最大)


0
投票

亲爱的评审员,

这里的解决方案,我已经工作了感谢另一个帖子,我希望再次找到,以给予正确的信用。

fig, axs = plt.subplots(2,2)

def plot_ff(ax=None,data):
   ax.plot(data)
   return

plot_ff(axs[0, 0],data_1)
plot_ff(axs[0, 1],data_2)
plot_ff(axs[1, 0],data_3)
plot_ff(axs[0, 1],data_3)

在这种方式,它的工作原理,它是很容易管理与不同类型的多图。

你觉得这个解决方案怎么样?我应该删除这个问题吗?

© www.soinside.com 2019 - 2024. All rights reserved.