I have a main program main.py
in which I call various functions with the idea that each function plots something to 1 figure. ie 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?
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.