Show objects with display#

IPython can display objects such as HTML, JSON, PNG, JPEG, SVG and Latex

Images#

To display images (JPEG, PNG) in IPython and notebooks, you can use the Image class:

[1]:
from IPython.display import Image
Image('https://www.python.org/images/python-logo.gif')
[1]:
<IPython.core.display.Image object>
[2]:
from IPython.display import SVG
SVG('https://upload.wikimedia.org/wikipedia/commons/c/c3/Python-logo-notext.svg')
[2]:
../../_images/workspace_ipython_display_3_0.svg

Non-embedded images#

  • By default, image data is embedded:

    Image ('img_url')
    
  • However, if the url is given as kwarg, this is interpreted as a soft link:

    Image (url='img_url')
    
  • embed can also be specified explicitly:

    Image (url='img_url', embed = True)
    

HTML#

Python objects can declare HTML representations to be displayed in a notebook:

[3]:
from IPython.display import HTML
[4]:
%%html
<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
  • foo
  • bar

Javascript#

With notebooks, objects can also declare a JavaScript representation. This enables for example data visualisations with Javascript libraries like d3.js.

[5]:
from IPython.display import Javascript


welcome = Javascript(
    'alert("Dies ist ein Beispiel für eine durch IPython angezeigte Javascript-Warnung.")'
)
display(welcome)

For more extensive Javascript you can also use the %%javascript syntax.

LaTeX#

IPython.display also has built-in support for displaying mathematical expressions set in LaTeX and rendered in the browser with MathJax:

[6]:
from IPython.display import Math


Math(r"F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx")
[6]:
$\displaystyle F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$

With the Latex class you have to specify the limits yourself. In this way, however, you can also use other LaTeX modes, such as eqnarray:

[7]:
from IPython.display import Latex


Latex(
    r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\end{eqnarray}"""
)
[7]:
\begin{eqnarray} \nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\ \end{eqnarray}

Audio#

IPython also enables interactive work with sounds. With the display.Audio class you can create an audio control that is embedded in the notebook. The interface is analogous to that of the Image class. All audio formats supported by the browser can be used.

[8]:
from IPython.display import Audio

In the following we will output the sine function of a NumPy array as an audio signal. The Audio class normalises and codes the data and embeds the resulting audio in the notebook.

[9]:
import numpy as np


f = 500.0
rate = 8000
L = 3
times = np.linspace(0, L, rate * L)
signal = np.sin(f * times)

Audio(data=signal, rate=rate)
[9]:

Display notebooks#

[12]:
import os
import sys
import types

import nbformat

from IPython.display import HTML, display
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import PythonLexer


formatter = HtmlFormatter()
lexer = PythonLexer()

# publish the CSS for pygments highlighting
display(
    HTML(
        """
<style type='text/css'>
%s
</style>
"""
        % formatter.get_style_defs()
    )
)
[13]:
def show_notebook(fname):
    """display a short summary of the cells of a notebook"""
    nb = nbformat.read(fname, as_version=4)
    html = []
    for cell in nb.cells:
        html.append("<h4>%s cell</h4>" % cell.cell_type)
        if cell.cell_type == "code":
            html.append(highlight(cell.source, lexer, formatter))
        else:
            html.append("<pre>%s</pre>" % cell.source)
    display(HTML("\n".join(html)))


show_notebook(os.path.join("mypackage/foo.ipynb"))

markdown cell

# `foo.ipynb`

code cell

def bar():
    return "bar"

code cell

def dirlist():
    listing = !ls
    return listing

code cell

def whatsmyname():
    return __name__