如何使用 matplotlib 绘制平方函数

How to plot square function with matplotlib

我有一个在 0 和 1 之间交替的值列表,例如 [0,1,0,1,0],我想用 matplotlib 将它们绘制成方波 python.到目前为止我有这个:

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()

这给了我这样的输出 :

我如何做到这一点,而不是在点之间形成一个角度,直线保持平坦?

我找到了这个 但它更多地涉及动画,而不仅仅是绘制函数。

您引用的 post 中的相关位是 drawstyle:

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

“初级,华生!”

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()