简体   繁体   English

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

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

I have two files with data: datafile1 and datafile2, the first one always is present and the second one only sometimes. 我有两个带有数据的文件:datafile1和datafile2,第一个始终存在,而第二个仅有时存在。 So the plot for the data on datafile2 is defined as a function (geom_macro) within my python script. 因此,datafile2上数据的绘图在我的python脚本中定义为一个函数(geom_macro)。 At the end of the plotting code for the data on datafile1 I first test that datafile2 is present and if so, I call the defined function. 在datafile1上数据的绘图代码结尾处,我首先测试datafile2是否存在,如果存在,则调用已定义的函数。 But what I get in the case is present, is two separate figures and not one with the information of the second one on top of the other. 但是,在这种情况下,我得到的是两个单独的数字,而不是一个,而第二个则位于另一个之上。 That part of my script looks like this: 我的脚本的该部分如下所示:

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()

The "geom_macro" function looks like this: “ 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>

Is there a way like "append" statement used for adding elements in a list, that can be used within matplotlib pyplot to add a plot to an existing one? 有没有一种类似于“ append”语句的方法用于在列表中添加元素,该方法可以在matplotlib pyplot中用于将图添加到现有图? Thanks for your help! 谢谢你的帮助!

Call 呼叫

fig, ax = plt.subplots()

once. 一旦。 To add multiple plots to the same axis, call ax 's methods: 要将多个图添加到同一轴,请调用ax的方法:

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

Do not call f = plt.figure() twice. 不要两次调用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()

You do not have to make ax an argument of geom_macro -- if ax is in the global namespace, it will be accessible from within geom_macro anyway. 不必做 ax的说法geom_macro -如果ax是在全局命名空间,这将是从内部访问geom_macro反正。 However, I think it is cleaner to state explicitly that geom_macro uses ax , and, moreover, by making it an argument, you make geom_macro more reusable -- perhaps at some point you will want to work with more than one subplot and then it will be necessary to specify on which axis you wish geom_macro to draw. 但是,我认为更明确地声明geom_macro使用ax更为干净,而且,通过将其作为参数,可以使geom_macro更具可重用性-也许在某个时候,您将需要使用多个子图,然后它将必须指定您希望geom_macro在哪个轴上绘制。

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

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