【问题标题】:Using plots returned from functions as subplots in Python使用从函数返回的图作为 Python 中的子图
【发布时间】:2021-02-10 23:58:03
【问题描述】:

我在使用 Python 时遇到的大多数问题都与绘图有关...

在我的代码中,我有两个函数,每个函数都有多个输出。这些函数作为返回值,例如,plot_periodogram 函数返回 best_period、period_error,并且在使用时也会给出一个图。 另一个函数 fold_LC 在使用时会给出一个绘图结果。

我想要做的是将这些结果图用作图中的子图。我试图将图保存在变量中并返回它们,将它们绘制在函数旁边的轴上,以及我在互联网上找到的所有解决方案,但没有任何效果。这是一个例子:IPython/matplotlib: Return subplot from function

有没有办法将这些函数中获得的图存储在一个变量中,然后将它们用作子图?

我的代码中有两个函数。

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')

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    标准方法与您尝试做的相反。
    不要从函数返回子图,而是将子图传递给它。

    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))
    

    请记住,您可以使用plt 命名空间中的函数执行的所有操作也可以执行using the methods of the graphical objects that Matplotlib provides you

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 2019-10-21
      • 2019-03-28
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 2013-11-09
      相关资源
      最近更新 更多