I have a class with methods to build some plots. I try to display different plots on one figure. The properties (title, legend…) of the figure are always overwritten by the last plot. I expected that if I have return in my method the behaviour would be different to the method without it, but it seems to not be true.
I would like to figure out what difference makes to have return. The code to illustrate my question is:
import matplotlib.pyplot as plt
import numpy as np
class myClass1(object):
def __init__(self):
self.x = np.random.random(100)
self.y = np.random.random(100)
def plotNReturn1(self):
plt.plot(self.x,self.y,'-*',label='randNxy')
plt.title('Plot No Return1')
plt.legend(numpoints = 1)
def plotNReturn2(self):
plt.plot(self.y,self.x,'-x',label='randNzw')
plt.title('Plot No Return2')
plt.legend(numpoints = 2)
def plotWReturn1(self):
fig = plt.plot(self.x,self.y,'-*',label='randWxy')
fig = plt.title('Plot With Return1')
fig = plt.legend(numpoints = 1)
return fig
def plotWReturn2(self):
fig = plt.plot(self.y,self.x,'-x',label='randWzw')
fig = plt.title('Plot With Return2')
plt.legend(numpoints = 3)
return fig
if __name__=='__main__':
f = myClass1()
p = plt.figure()
p1 = p.add_subplot(122)
p1 = f.plotWReturn1()
p1 = f.plotWReturn2()
print 'method with return: %s: ' % type(p1)
p2 = p.add_subplot(121)
p2 = f.plotNReturn1()
p2 = f.plotNReturn2()
print 'method without return: %s: ' % type(p2)
plt.show()
The only difference I noticed is the type of the output, but I don’t know what it means in practice.
method with return: <class 'matplotlib.text.Text'>:
method without return: <type 'NoneType'>:
Is it only about “pythonic” practice or is there anything practical to use any of the style?
Returning a value has only a direct effect for the caller, in this case your
__main__block. If you don’t need to reuse some value computed by a function, in your case assigned to p1 or p2, the return doesn’t have any impact on behaviour.Also, series of assignments like
are indicators of bad code style, because only the last value assigned to p1 is going to be available after them.
Anyway, I think you want to plot on subplots, as opposed to the main plot, like so:
Here, subplot is passed to each function, so data should be plotted on it, instead of replacing what you’ve plotted before.