Skip to content

Instantly share code, notes, and snippets.

@JanWilczek
Created February 1, 2024 16:45
Show Gist options
  • Select an option

  • Save JanWilczek/ccda1ea11a4288780548a4977b413d29 to your computer and use it in GitHub Desktop.

Select an option

Save JanWilczek/ccda1ea11a4288780548a4977b413d29 to your computer and use it in GitHub Desktop.
Easily plot an audio signal as a continuous waveform and (optionally) save to a file. Uses matplotlib for plotting and saving the figure, pathlib for path handling, and numpy for sine generation. I use this snippet all the time to plot signals and inspect outputs of an audio system. Feel free to treat it as a template: copy, paste & tweak accord…
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
IMG_OUTPUT_PATH = Path('img')
SAVE_PARAMS = {'dpi': 300, 'bbox_inches': 'tight', 'transparent': True}
def plot_signal(signal, time=None):
plt.rcParams.update({'font.size': 20})
COLOR = '#ef7600'
samples_count = signal.shape[0]
plt.figure(figsize=(12,6))
if time is None:
xlim = [0, samples_count]
plt.plot(signal, COLOR, linewidth=3)
plt.xlabel('samples')
else:
xlim = [time[0], time[-1]]
plt.plot(time, signal, COLOR, linewidth=3)
plt.xlabel('time [s]')
plt.hlines(0, xlim[0], xlim[1], 'k')
plt.ylabel('amplitude')
plt.xlim(xlim)
plt.yticks([-1, 0, 1])
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
def plot_signal_and_save(signal, output_path, time=None):
plot_signal(signal, time)
# plt.show() # closes the figure
output_path.parent.mkdir(parents=True, exist_ok=True)
plt.savefig(output_path, **SAVE_PARAMS)
plt.close()
def main():
frequency = 440
sample_rate = 44100
length_seconds = 5
time = np.arange(length_seconds * sample_rate) / sample_rate
sine = np.sin(2 * np.pi * frequency * time)
plot_signal_and_save(sine[:1000], IMG_OUTPUT_PATH / 'sine_signal.png', time[:1000])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment