Skip to content

Instantly share code, notes, and snippets.

@yolisses
Created February 21, 2023 15:16
Show Gist options
  • Save yolisses/d0fd9eb590e6edf21072845155d782ae to your computer and use it in GitHub Desktop.
Save yolisses/d0fd9eb590e6edf21072845155d782ae to your computer and use it in GitHub Desktop.
Plot MIDI in Python with pretty_midi and pyplot
import pretty_midi as pm
from itertools import cycle
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def plot_midi(midi: pm.PrettyMIDI):
fig, ax = plt.subplots()
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
colors = cycle(colors)
for instrument in midi.instruments:
color = next(colors)
for note in instrument.notes:
rectangle = patches.Rectangle(
[note.start, note.pitch],
note.end - note.start, 1,
facecolor=color
)
ax.add_patch(rectangle)
rectangle = patches.Rectangle(
[note.start, note.pitch],
0.05, 1,
facecolor='#0004',
)
ax.add_patch(rectangle)
ax.plot()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment