python - 如何使用 matplotlib 在轴上绘制带有参数的函数

标签 python matplotlib plot trigonometry

我想绘制函数

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, 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}$')

关于python - 如何使用 matplotlib 在轴上绘制带有参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63837586/

相关文章:

python - 使用 matplotlib 从数据帧绘制向量?

python - 使用 matplotlib 创建子图

python - 如何为极坐标图中的圆形线着色(matplotlib)

google-apps-script - Google Sheet/Google Script - 在图片上绘制点

R 插值极坐标等值线图

plot - 如何在 wxMaxima 工作表中设置 wxplot2d 图的大小?

python - python中的模板

python - Azure get_blob 仅返回 4KB 的图像大小

python - 删除与另一个 CSV 中的行相同的行

python - 如何生成随机数的直方图?