5

I have an list of values that alternate between 0 and 1, eg [0,1,0,1,0] and I want to graph them so they appear as a square wave using matplotlib for python. I have this so far:

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 gives me an output like this this:

How do I make it so instead of going on an angle between the points the line stays flat?

I found this post but it deals more with an animation and not just plotting the function.

2 Answers 2

17

The relevant bit from that post you reference is the drawstyle:

 plt.plot(input_amp, marker='d', color='blue', drawstyle='steps-pre')
Sign up to request clarification or add additional context in comments.

1 Comment

drawstyle='steps-post' is more commonly used.
-1

"Elementary, Watson!"

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 Comment

The amplitude of this waveform is from 1 to -1. Can you please show how can extend this wave from 0 to 2 instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.