python - 如何使用 matplotlib 在轴上绘制带有参数的函数
问题描述
我想绘制函数
直到求和有限 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()
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}$')
推荐阅读
- javascript - 类型函数中的嵌套泛型
- python-3.x - 多个输入和行循环写入文件 - python
- php - 带有数据范围的 Mysqli 通配符插入
- python - 字符串转换,然后是 int 和 int 转换的字符串之间的区别
- firebase - Firestore 食品订购应用程序数据库设计问题
- r - data.frame 选择有条件的列
- react-native-android - 如何在反应原生导航 v5 中重置堆栈
- python-3.x - 即使添加 encoding='utf-8' 命令,Unicode 错误也不会消失
- javascript - 转换数组数组,并返回一个对象,数组中的每一对元素作为键值对
- mongodb - MongoDB查询-展开并匹配保留null或不同的值/根据条件添加新字段