how to add a plot on top of another plot in matplo

2020-07-24 06:09发布

问题:

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

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>

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!

回答1:

Call

fig, ax = plt.subplots()

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

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

Do not call f = plt.figure() twice.


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