Python 如何在matplotlib中的另一个图上添加一个图?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17603678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add a plot on top of another plot in matplotlib?
提问by jealopez
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:
我有两个包含数据的文件: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()
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? Thanks for your help!
有没有一种像“追加”语句用于在列表中添加元素的方法,可以在 matplotlib pyplot 中使用它来将图添加到现有的图?谢谢你的帮助!
采纳答案by unutbu
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 tomake 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.
你不必须做出ax
的一个参数geom_macro
-如果ax
是在全局命名空间,这将是从内部访问的geom_macro
反正。但是,我认为明确说明geom_macro
uses会更清晰ax
,而且,通过将其作为参数,您可以geom_macro
提高可重用性——也许在某些时候您会想要处理多个子图,然后有必要指定要在哪个轴上geom_macro
绘制。