python中的正弦绘图

2024-09-30 23:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该如何绘制矩形顶部有正弦的图形? 我用代码画了一个矩形:

def rectdraw(length_sec=1000):
    rect = []
    for time in range(0, 3000, 1):
        if time > 1000 and time < 2000:
            rect.append(1.2)
        else:
            rect.append(0)
    plt.figure()
    plt.plot(rect)
    plt.show() 

但是我应该得到一个正弦波,而不是值1.2。我应该如何修改我的代码

rectangular image


Tags: 代码inrect图形fortimedef绘制
1条回答
网友
1楼 · 发布于 2024-09-30 23:39:55

正弦函数如下所示:

enter image description here

因此,在使用正弦函数时,需要定义振幅、频率和相位。所以,我稍微改变了你的函数,它接受了另外三个参数:

  • 振幅a(1为默认值)
  • 频率freq(默认值为0.005)
  • 阶段ph(0作为默认值)
def rectdraw(a=1, freq=0.005, ph=0, length_sec=1000):
    rect = []
    for time in range(0, 3000, 1):
        if time > 1000 and time < 2000:
            rect.append(1.2+(a*np.sin(2*np.pi*freq*time + ph)))
        else:
            rect.append(0)
    plt.figure()
    plt.plot(rect)
    plt.show()

运行上一个函数会生成以下图形: enter image description here

相关问题 更多 >