繁体   English   中英

如何在matplotlib中的另一个图的顶部添加图?

[英]how to add a plot on top of another plot in matplotlib?

我有两个带有数据的文件:datafile1和datafile2,第一个始终存在,而第二个仅有时存在。 因此,datafile2上数据的绘图在我的python脚本中定义为一个函数(geom_macro)。 在datafile1上数据的绘图代码结尾处,我首先测试datafile2是否存在,如果存在,则调用已定义的函数。 但是,在这种情况下,我得到的是两个单独的数字,而不是一个,而第二个则位于另一个之上。 我的脚本的该部分如下所示:

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>

有没有一种类似于“ append”语句的方法用于在列表中添加元素,该方法可以在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在哪个轴上绘制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM