首页 > 解决方案 > 如何使用 matplotlib 在轴上绘制带有参数的函数

问题描述

我想绘制函数

在此处输入图像描述

直到求和有限 k。我将从水平轴获取 t 值。

到目前为止我所拥有的:

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

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

标签: pythonmatplotlibplottrigonometry

解决方案


您可以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()

示例图

PS:你可以玩转 numpy 的广播并一次性计算 f 值。该函数需要稍作调整,取中间矩阵的列的总和:

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

推荐阅读