How to display a YouTube video and matplotlib plot side by side on Jupyter notebook?

Viewed 275

I'm writing an interactive Jupyter notebook using Ipython and I would like to display a YouTube video side by side with a matplotlib plot. Each displays properly in itself, but as I try to display them within an HBox they appear one below the other instead of next to each other horizontally. I tried shrinking them, but the behaviour did not change. Here's an example worked from another one found at kapernikov.com

import ipywidgets as widgets
from IPython.display import display
import numpy as np
import matplotlib.pyplot as plt


SalidaEjes = widgets.Output()

x = np.linspace(0, 2 * np.pi, 100)

with SalidaEjes:
    fig, ax = plt.subplots(figsize=(3, 2))
    line, = ax.plot(x, np.sin(x))

from IPython.display import YouTubeVideo

SalidaVideo = widgets.Output()

with SalidaVideo:
    display(YouTubeVideo('RdMj0iMCYfE', width=200, height=200))

Salidas = widgets.HBox([SalidaEjes, SalidaVideo])
display(Salidas)

I guess I'm making an obvious mistake but I don't know where. Any help is appreciated! Best regards.

1 Answers

What you are seeing is the HBox display with empty SalidaEjes on the left and then the auto-generated plot below (so HBox works ok!). You need to show the plot within the SalidaEjes context so that it is not appended after the HBox and shown within HBox/SalidaEjes:

with SalidaEjes:
    x = np.linspace(0, 2 * np.pi, 100)
    fig, ax = plt.subplots(figsize=(3, 2));
    line, = ax.plot(x, np.sin(x))
    plt.show(fig)  # <-- here

This is related to https://stackoverflow.com/a/51060721/6646912.

Related