gpt4 book ai didi

python - 如何在 matplotlib 中的另一个图之上添加一个图?

转载 作者:行者123 更新时间:2023-11-28 22:54:49 25 4
gpt4 key购买 nike

我有两个包含数据的文件:datafile1 和 datafile2,第一个总是存在,第二个仅有时存在。因此,datafile2 上的数据图在我的 python 脚本中被定义为一个函数 (geom_macro)。在数据文件 1 上数据的绘图代码结束时,我首先测试数据文件 2 是否存在,如果存在,我将调用定义的函数。但是我在这个案例中得到的是两个独立的数字,而不是一个将第二个的信息放在另一个之上。我脚本的那部分看起来像这样:

f = plt.figuire()
<in this section a contour plot is defined of datafile1 data, axes, colorbars, etc...>

if os.path.isfile('datafile2'):
geom_macro()

plt.show()

“geom_macro”函数如下所示:

def geom_macro():
<Data is collected from datafile2 and analyzed>
f = plt.figure()
ax = f.add_subplot(111)
<annotations, arrows, and some other things are defined>

有没有像“追加”语句那样用于在列表中添加元素的方法,可以在 matplotlib pyplot 中使用它来将绘图添加到现有绘图中?感谢您的帮助!

最佳答案

打电话

fig, ax = plt.subplots()

一次。要将多个绘图添加到同一轴,请调用 ax 的方法:

ax.contour(...)
ax.plot(...)
# etc.

不要调用 f = plt.figure() 两次。


def geom_macro(ax):
<Data is collected from datafile2 and analyzed>
<annotations, arrows, and some other things are defined>
ax.annotate(...)

fig, ax = plt.subplots()
<in this section a contour plot is defined of datafile1 data, axes, colorbars, etc...>

if os.path.isfile('datafile2'):
geom_macro(ax)

plt.show()

不必使 ax 成为 geom_macro 的参数——如果 ax 在全局中命名空间,无论如何都可以从 geom_macro 中访问它。但是,我认为明确声明 geom_macro 使用 ax 更清晰,而且,通过将其作为参数,您可以使 geom_macro 更多可重用——也许在某些时候您会想要处理多个子图,然后有必要指定您希望 geom_macro 在哪个轴上绘制。

关于python - 如何在 matplotlib 中的另一个图之上添加一个图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17603678/

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