如何使用Matplotlib绘制平方函数图形

5

我有一个值列表,其中的值在0和1之间交替出现,例如[0,1,0,1,0],我想使用Python的matplotlib将它们绘制成正弦波形式。目前我的代码如下:

input_amp = [1,0,1,0,1,0,1,0,1,0]
plt.plot(input_amp, marker='d', color='blue')
plt.title("Waveform")
plt.ylabel('Amplitude')
plt.xlabel("Time")
plt.savefig("waveform.png")
plt.show()

这将给我一个类似这样的输出this:

如何使线条保持平直,而不是在点之间呈角度?
我找到了这篇文章,但它更多地涉及动画而不仅仅是绘制函数。
2个回答

17

您参考的那篇文章中相关的部分是drawstyle

 plt.plot(input_amp, marker='d', color='blue', drawstyle='steps-pre')

1
drawstyle='steps-post' 更常用。 - Kyung Lee

-1

“初级的,华生!”

import matplotlib.pyplot as plot
import numpy as np

# Sampling rate 1000 hz / second
t = np.linspace(0, 1, 100, endpoint=True)

# Plot the square wave signal
plot.plot(t, signal.square(2 * np.pi * 1 * t))

# A title for the square wave plot
plot.title('1Hz square wave sampled at 100 Hz /second')

# x axis label for the square wave plot
plot.xlabel('Time')
    
# y axis label for the square wave plot
plot.ylabel('Amplitude')
plot.grid(True, which='both')

# Provide x axis and line color
plot.axhline(y=0, color='k')

# Set the max and min values for y axis
plot.ylim(-1.2, 1.2)

# Display the square wave
plot.show()

square wave


这个波形的振幅从1到-1。您能否展示如何将此波形从0扩展到2? - Mavis_Ackerman

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