【问题标题】:How can I plot output from a function which returns multiple values in Python?如何绘制在 Python 中返回多个值的函数的输出?
【发布时间】:2016-02-18 16:19:37
【问题描述】:

简介

我正在根据给定的数据计算和绘制围绕脉冲星运行的行星的光谱能量。

我之前已将列表变体中的所有数据排序,维度为 [172, 2](172 行和 2 列)。

首先,我必须相应地计算预设模型的参数和光谱能量(根据这些参数)。

为此,我定义了一个函数,在该函数下定义了预设模型和获取模型和变化数据的 find_fit 函数。

代码

 var('a, b, t')

def spectrum(omega):

    model = a*sin(omega*t) + b*cos(omega*t)
    fit = find_fit(variations, model, parameters= [a, b], variables = [t], solution_dict = True)
    sp_en = ((fit[a])**2 + (fit[b])**2)/2

    return fit[a], fit[b], sp_en

然后我调用函数并打印值:

c, v, energy = spectrum(20)   #enter arbitray angular frequency here
print "Values for the given angular frequency : \n \n a = %f, b = %f, spectral_energy = %f " % (c, v, energy)

现在我必须绘制 only sp_en 输出。

“半解”

如果 spectrum 函数返回 仅 sp_en,这很容易。写就够了:

var('t')
plot(spectrum(t), (t, 1, 100))

返回: energy-omega plot


问题是:如果我想打印所有三个输出,如何绘制这个函数?

【问题讨论】:

    标签: python matplotlib plot physics multipleoutputs


    【解决方案1】:

    只需对频谱的返回值使用索引:

    plot(spectrum(t)[2], (t, 1, 100))
    

    【讨论】:

    • 感谢您的回答。我不知道我可以以这种方式使用索引。索引确实只绘制了能量图。但还是少了点什么。这是正确的解决方案。 plot(lambda t:spectrum(t)[2], (t, 1, 100))
    【解决方案2】:

    只需使用energy 变量调用绘图函数

    omega=10
    c, v, energy = spectrum(omega)   #enter arbitray angular frequency here
    print "Values for the given angular frequency : \n \n a = %f, b = %f, spectral_energy = %f " % (c, v, energy)
    

    plot(energy, (omega, 1, 100))

    【讨论】:

    • 感谢您的回答。这条线行不通。我收到错误消息:“未定义变量 omega”。
    • 我刚刚从你的函数中重用了它。定义,经过编辑,现在可以使用了。
    猜你喜欢
    • 2010-09-30
    • 1970-01-01
    • 2019-05-10
    • 2020-06-20
    • 1970-01-01
    • 2019-03-15
    • 2015-02-23
    • 2019-02-07
    • 2013-03-14
    相关资源
    最近更新 更多