Reputation: 13
Most of the problems I have with Python is related to plotting stuff...
In my code I have two functions that have more than one output each one. Those functions give as return, for example, the plot_periodogram function returns best_period, period_error and also when used it gives a plot. The other function fold_LC when used gives a plot as a result.
What I'm trying to do is to use those resulting plots as subplots in a figure. Ihave tried to save the plots in varibles and returning them, to plot them in axes in side the functions, and all the solutions that I've found on the internet but nothing worked. Here is an example: IPython/matplotlib: Return subplot from function
Is there any way to store in a variable the plots obtained in those functions and then use them as subplots?
Here you have the two functions in my code.
def plot_periodogram(curva_corregida):
gls = Gls(lc,fbeg=None, fend=None,Pbeg=min_t,Pend=max_t)
best_period = gls.best['P']
period_error = gls.best['e_P']
period = 1/gls.freq
power = gls.power
max_power = power.max()
plt.plot(period,power,'b-',linewidth=.8)
plt.scatter(best_period,max_power,c='r',s=4,label='P={0} d'.format(round(best_period,4)))
plt.legend(loc='best')
return best_period, period_error
def fold_LC(curva_corregida, best_period):
folded = curva_corregida.fold(period = best_period)
lc_flux_folded = folded.flux
lc_time_folded = folded.phase
plt.scatter(lc_time_folded,lc_flux_folded,s=0.5, color='b')
Upvotes: 1
Views: 1237
Reputation: 25023
The standard approach is the opposite to what you're trying to do.
Do not return the subplot from the function but rather pass the subplot to it.
import numpy as np, matplotlib.pyplot as plt
def plot_periodogram(subplot, curva_corregida):
gls = Gls(lc,fbeg=None, fend=None,Pbeg=min_t,Pend=max_t)
best_period = gls.best['P']
period_error = gls.best['e_P']
period = 1/gls.freq
power = gls.power
max_power = power.max()
subplot.plot(period,power,'b-',linewidth=.8)
subplot.scatter(best_period,max_power,c='r',s=4,label='P={0} d'.format(round(best_period,4)))
subplot.legend(loc='best')
fig, subplots = plt.subplots(nrows=2, ncols=3)
for n, subplot in enumerate(subplots.flatten()):
plot_periodogram(subplot, curva_corregida(n))
Remember that everything that you can do using the functions in the plt
namespace can be done also using the methods of the graphical objects that Matplotlib provides you.
Upvotes: 1