尝试绘制傅里叶正弦函数

3
from matplotlib import markers
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap

plt.rcParams['figure.figsize'] = [9,9]
plt.rcParams.update({'font.size' : 16})

#domain definition
dx = 0.01 #input("input the step size: ")
x = np.pi*np.arange(-1+ float(dx),1+float(dx),float(dx))
n = len(x)
nquart = int(np.floor(n/4))

#hat funtion
f = np.zeros_like(x)
f[nquart : 2*nquart] = (4/n)*np.arange(1,nquart+1)
f[2*nquart:3*nquart] = np.ones(nquart) - (4/n)*np.arange(0,nquart)

#subplot creation
fig,ax = plt.subplots(1)
ax.plot(x,f)

#core fourier series
name = 'accent'
cmap = get_cmap('tab10')
colors = cmap.colors
ax.set_prop_cycle(color = colors)

# sum of values with an array of ones with the same shape and type as a given array.
Ao = np.sum(f*np.ones_like(x))*dx
ffs = Ao/2

A = np.zeros(20)
B = np.zeros(20)

for k in range(20):
    #the inner products
    A[k] = np.sum(f*np.cos(np.pi*(k+1)*(x/np.pi)))*dx
    B[k] = np.sum(f*np.sin(np.pi*(k+1)*(x/np.pi)))*dx

    ffs = ffs + A[k]*np.cos((k+1)*np.pi*(x/np.pi)) + B[k]*np.sin((k+1)*np.pi*(x/np.pi))
    ax.plot(x,ffs,markers = 'o',LineWidth = 1.5)
    plt.show()

运行代码时出现错误属性错误:'Line2D'对象没有属性'markers','LineWidth' 如果不使用markers和LineWidth,则代码可以运行,但是预期的结果不是我想要的 我得到了大约15个图形,但这不是我想要的颜色样式也没有应用


你为什么要在 marker= 后面加上一个 s,并且用两个大写字母写 linewidth=?请参考 ax.plot() 文档。此外,你可能想要在 for 循环结束后只调用一次 plt.show(),而不是连续多次调用。 - JohanC
谢谢你,我差点忘了那个...我已经纠正了,非常感谢。 - Nugget
1个回答

1
属性错误:'Line2D'对象没有属性'markers'和'LineWidth' 这是因为应该使用“marker”和“linewidth”: 进行这些更改,并将“plt.show()”从循环中取出:
for k in range(20):
    #the inner products
    A[k] = np.sum(f*np.cos(np.pi*(k+1)*(x/np.pi)))*dx
    B[k] = np.sum(f*np.sin(np.pi*(k+1)*(x/np.pi)))*dx

    ffs = ffs + A[k]*np.cos((k+1)*np.pi*(x/np.pi)) + B[k]*np.sin((k+1)*np.pi*(x/np.pi))
    ax.plot(x,ffs,marker = 'o',linewidth = 1.5)
    
plt.show()

...我们得到: 在此输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接