The following code display the image
and audio
in the top-bottom
style:
Here is the test code:
JavaScript
x
13
13
1
import librosa
2
import matplotlib.pyplot as plt
3
import IPython.display as ipd
4
5
def plot_it(name, audio, sample_rate):
6
plt.figure(figsize=(8, 1))
7
plt.plot(audio)
8
plt.gca().set_title(name)
9
10
plt.show()
11
12
ipd.display(ipd.Audio(data=audio, rate=sample_rate))
13
Is it possible for changing the “top-bottom
” style to “left-right
” style for displaying the audio
at the right side of the plt
figure?
Advertisement
Answer
You can use a GridspecLayout
which is similar to matplotlib’s GridSpec
. In order to direct to output into the needed grid cells, you can capture it using the Output
widget:
JavaScript
1
27
27
1
import librosa
2
import matplotlib.pyplot as plt
3
import IPython.display as ipd
4
from ipywidgets import Output, GridspecLayout
5
6
def plot_it(name, audio, sample_rate):
7
grid = GridspecLayout(1, 2, align_items='center')
8
out = Output()
9
with out:
10
fig, ax = plt.subplots(figsize=(8, 1))
11
ax.plot(audio)
12
ax.set_title(name)
13
plt.close(fig)
14
ipd.display(ax.figure)
15
grid[0, 0] = out
16
out = Output()
17
with out:
18
ipd.display(ipd.Audio(data=audio, rate=sample_rate))
19
grid[0, 1] = out
20
ipd.display(grid)
21
22
name = 'nutcracker'
23
filename = librosa.example(name)
24
y, sr = librosa.load(filename)
25
26
plot_it(name, y, sr)
27
(It is essential to close the figure
, otherwise you’ll have double output of the figure. This is easier to do this using the OOP than the pyplot interface, that’s why I changed your matplotlib code a bit)