如何使用Matplotlib在轴上绘制带有参数的函数

问题描述

我想绘制函数

enter image description here

最多加和有限的k。我将从水平轴取t值。

到目前为止我所拥有的:

def f_func(n,t):
     summation = sum([np.sin(k*t)/k for k in range(n)])
     return summation

现在我有函数,我想告诉matplotlib将其水平轴用作时间参数,同时选择一个特定的k参数。我该怎么做呢?

解决方法

您可以循环调用f_func并将值放在列表中。请注意,求和必须从k=1开始,以防止被零除。

以下示例代码为n的连续值创建曲线:

from matplotlib import pyplot as plt
import numpy as np

def f_func(n,t):
    summation = sum([np.sin(k * t) / k for k in range(1,n + 1)])
    return summation

ts = np.linspace(-5,12.5,200)
for n in range(1,11):
    fs = [f_func(n,t) for t in ts]
    plt.plot(ts,fs,label=f'$n={n}$')
plt.margins(x=0,tight=True)
plt.xlabel('$t$')
plt.ylabel('$f(n,t)$')
plt.legend(ncol=2)
plt.show()

example plot

PS:您可以使用numpy的broadcasting并一次性计算f值。需要对函数进行一点调整,并采用中间矩阵的列总和:

ts = np.linspace(-5,200)
ks = np.arange(1,n+1).reshape(-1,1)
fs = np.sum(np.sin(ks * ts) / ks,axis=0)
plt.plot(ts,label=f'$n={n}$')
,

免责声明:matplotlib很大,我跳过了很多现在可能无关紧要的细节。

在matplotlib中,您不使用水平轴作为时间参数。定义水平轴,定义垂直轴,如果两者之间存在某种关系,则需要小心进行显式编码。

def f_func(n,t):
    k = np.arange(1,n)  # none of that pesky division by 0
    return np.sum(np.sin(t*k)/k)

# This will be our horizontal axis; use whichever
# t-values you want. We're using [0,1,...,99] 
# as an example.
horizontal = np.arange(100)

# Corresponds exactly to how many terms of
# the summation you're considering.
n = 42

# Using the horizontal axis as the time parameter is
# accomplished by explicitly creating the horizontal
# axis as the time parameter (which we've already
# done) and ensuring the vertical axis uses the
# function we want to plot.
vertical = [f_func(n,t) for t in horizontal]

# Actual plotting stuff. Tweak as needed.
plt.plot(horizontal,vertical)
plt.show()