如何在matplotlib中的另一个图上添加一个图

如何在matplotlib中的另一个图上添加一个图

本文介绍了如何在matplotlib中的另一个图上添加一个图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two files with data: datafile1 and datafile2, the first one always is present and the second one only sometimes. So the plot for the data on datafile2 is defined as a function (geom_macro) within my python script. 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. 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()

geom_macro"函数如下所示:

The "geom_macro" function looks like this:

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 中用于向现有的添加一个图?感谢您的帮助!

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?Thanks for your help!

推荐答案

致电

fig, ax = plt.subplots()

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

once. To add multiple plots to the same axis, call ax's methods:

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 在哪个轴上绘制.

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. 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.

这篇关于如何在matplotlib中的另一个图上添加一个图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 12:44