Reputation: 1368
I have a main program main.py
in which I call various functions with the idea that each function plots something to 1 figure. i.e. all the function plots append detail to the 1 main plot.
Currently I have it set up as, for example:
main.py:
import matplotlib.pylab as plt
a,b,c = 1,2,3
fig = func1(a,b,c)
d,e,f = 4,5,6
fig = func2(d,e,f)
plt.show()
func1:
def func1(a,b,c):
import matplotlib.pylab as plt
## Do stuff with a,b and c ##
fig = plt.figure()
plt.plot()
return fig
func2:
def func2(d,e,f):
import matplotlib.pylab as plt
## Do stuff with d,e and f ##
fig = plt.figure()
plt.plot()
return fig
This approach is halfway there but it plots separate figures for each function instead of overlaying them.
How can I obtain 1 figure with the results of all plots overlaid on top of each other?
Upvotes: 1
Views: 4829
Reputation: 31339
This should work. Note that I only create one figure and use the pyplot
interface to plot to it without ever explicitly obtaining a reference to the figure object.
import matplotlib.pyplot as plt
a = [1,2,3]
b = [3,2,1]
def func1(x):
plt.plot(x)
def func2(x):
plt.plot(x)
fig = plt.figure()
func1(a)
func2(b)
Upvotes: 3
Reputation: 87366
It is much better to use the OO interface for this puprose. See http://matplotlib.org/faq/usage_faq.html#coding-styles
import matplotlib.pyplot as plt
a = [1,2,3]
b = [3,2,1]
def func1(ax, x):
ax.plot(x)
def func2(ax, x):
ax.plot(x)
fig, ax = plt.subplots()
func1(ax, a)
func2(ax, b)
It seems silly for simple functions like this, but following this style will make things much much less painful when you want to do something more sophisticated.
Upvotes: 4