gpt4 book ai didi

python - 将数字添加到子图

转载 作者:行者123 更新时间:2023-12-01 09:27:17 25 4
gpt4 key购买 nike

我是 matplotlib 的新手,正在尝试了解如何将数字添加到子图中。

我有三个不同的函数,它们输出一个数字:

def plot_fig_1(vars, args):
f, ax, put.subplots()
# do something
ax.plot(x, y)
return f, ax


def plot_fig_2(vars, args):
f, ax, put.subplots()
# do something
ax.plot(x, y)
return f, ax

现在,例如,我想将两个图形合并到具有共享 X 轴的单个图中。我尝试过:

f_1, ax_1 = plot_fig_1(...)
f_2, ax_2 = plot_fig_2(...)

new_fig, new_ax = plt.subplots(2,1)
new_ax[0] = f_1
new_ax[1] = f_2

在这里我基本上迷失了。我正在阅读 Matplotlib 手册,但到目前为止还没有运气。

最佳答案

除非您的函数签名必须保持示例中定义的那样,否则在函数外部创建子图并将适当的 Axes 实例传递给每个函数会更容易。

def plot_fig_1(vars, args, ax):
# do something
ax.plot(x, y)

def plot_fig_2(vars, args, ax):
# do something
ax.plot(x, y)

fig, ax = plt.subplots(2, 1, sharex=True)
plot_fig_1(..., ax[0])
plot_fig_2(..., ax[1])

如果您需要创建一个仅包含其中一个子图的图形,您可以这样做:

fig, ax = plt.subplot()
plot_fig_1(..., ax)

或者,如果函数需要独立,请为 ax 参数指定一个默认值,并在函数内部测试它。

def plot_fig_1(vars, args, ax=None):
if ax is None:
fig, ax = plt.subplot()
# do something
ax.plot(x, y)

关于python - 将数字添加到子图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50279217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com