I am trying to implement this: https://stackoverflow.com/a/12025554/7718153 for matplotlib, but something goes wrong.
import matplotlib.pyplot as plt
if condition1:
q='plot'
elif condition2:
q='logy'
elif condition3
q='loglog'
m = globals()['plt']()
TypeError: 'module' object is not callable
plot_function = getattr(m, q) #it doens't make it to this line
I want it to do this:
if condition1:
plt.plot(...)
elif condition2:
plt.logy(...)
elif condition3:
plt.loglog(...)
Does anyone know what I do wrong?
Edit: I am sorry, I had my code in the wrong order. It's fixed now.
Edit2:
This is the code where it origionally came from:
def plot(self):
assert self.plotgraph == True
plt.figure(1)
plt.rcParams.update({'font.size': 40})
plt.figure(figsize=(150, 70))
plt.suptitle('alpha = '+str("{0:.2f}".format(self.alpha)))
j=len(self.seeds)
for k in range(9*j):
plt.subplot(3,3*j,k+1)
g=k%(3*j)
if k<3*j:
q='plot'
elif 3*j<=k<6*j:
q='logy'
elif 6*j<=k:
q='loglog'
m = globals()['plt']()
plot_function = getattr(m, q)
if g<2*j:
for i in range(j):
if (2*i)<=g%j*2<(2*(i+1)):
seed_type=' seed: '+ str(i+1)
seed=(i+1)
else:
for i in range(j):
if g%j == i:
seed_type=' seed: '+ str(i+1)
seed=(i+1)
if g<2*j:
if g%2==0:
set_type=' train-set'
plot_function(np.array(self.index),np.array(self.plotlist[seed*2+0]))
else:
set_type=' test-set'
plot_function(np.array(self.index),np.array(self.plotlist[seed*2+1]))
else:
set_type=' train-test dist'
plot_function(np.array(self.index),np.array(self.plotlist[seed*2+0]-np.array(self.plotlist[seed*2+1])))
plt.grid(True)
plt.title(q+set_type+seed_type)
plt.tight_layout()
plt.savefig("plot1() " +str(self.nodes[1])+' hidden nodes, alpha='+ str("{0:.2f}".format(self.alpha)) + '.png')
plt.clf()
plt.close()
m = globals()['plt']()
is the same thing as plt()
. plt
is a module so it isn't callable. I think you want:
m = globals()['plt']
plot_function = getattr(m, q)
plot_function() # call this one!
With that said... This design seems needlessly complex. Why not:
if condition1:
plt.plot()
elif condition2:
plt.logy()
elif condition3:
...