We start with a short presentation by Fernando Perez, founder of the IPython project. We use the notebook's rich display system to show the presentation - we'll how understand to do that soon.
from IPython.display import HTML
HTML('<script async class="speakerdeck-embed" data-id="5cd35ca0e91b01319d42227239d9f24b" data-ratio="1.33333333333333" src="//speakerdeck.com/assets/embed.js"></script>')
The notebook has a rich display system that uses the fact that the notebook runs in a browser - an multipotent rendering program capable of running JavaScript and specializing in interactive, graphical user interfaces.
The notebook allows objects to declare rich representations using different formats:
A single object can declare some or all of these representations; all are handled by the notebook display system.
This section follows Wojciech Jaśkowski's course notebook.
The display function is a general purpose tool for displaying different representations of objects. Think of it as print for these rich representations.
from IPython.display import display
A few points:
If you want to display a particular representation, there are specific functions for that:
from IPython.display import display_pretty, display_html, display_jpeg, display_png, display_json, display_latex, display_svg
To work with images (JPEG, PNG) use the Image class.
from IPython.display import Image
Returning an Image object from an expression will automatically display it:
i = Image(r'img\logo.png')
i
Or you can pass it to display:
display(i)
SVG images are also supported out of the box (since modern browsers do a good job of rendering them). Note that images can be loaded with a URL instead of a filename.
from IPython.display import SVG
SVG('https://www.python.org/static/community_logos/python-logo-generic.svg')
If we want to create a link to one of them, we can call use the FileLink object.
from IPython.display import FileLink, FileLinks
FileLink('if-while.ipynb')
Alternatively, if we want to link to all of the files in a directory, we can use the FileLinks object, passing '.' to indicate that we want links generated for the current working directory. Note that if there were other directories under the current directory, FileLinks would work in a recursive manner creating links to files in all sub-directories as well.
FileLinks('.')
By default, image data is embedded in the Notebook document so that the images can be viewed offline. However it is also possible to tell the Image class to only store a link to the image. Let's see how this works using a webcam at Berkeley.
By default Image data are embedded; here is the embedded version. Note that this image was pulled from the webcam when this code cell was originally run and stored in the Notebook. Unless we rerun this cell, this is not todays image.
berkeley_url = 'http://static.lawrencehallofscience.org/scienceview/scienceview.berkeley.edu/html/view/view_assets/images/newview.jpg'
embed = Image(berkeley_url)
embed
If kwarg url
is given, the embedding is assumed to be false.
Here is today's image from same webcam at Berkeley, (refreshed every minutes, if you reload the notebook), visible only with an active internet connection, that should be different from the previous one (unless you just re-run the previous cell).
Notebooks saved with this kind of image will be take less space and always reflect the current version of the source, but the image won't display offline.
soft_linked = Image(url=berkeley_url)
soft_linked
Of course, if you re-run this Notebook, the two images will be the same again.
In each case, embed can be specified explicitly with the embed
kwarg:
force_embed = Image(url=berkeley_url, embed=True)
force_embed
More exotic objects can also be displayed, as long as their representation supports the IPython display protocol. For example, videos hosted externally on YouTube are easy to load (and writing a similar wrapper for other hosted content is trivial):
from IPython.display import YouTubeVideo
# a talk about IPython at Sage Days at U. Washington, Seattle.
# Video credit: William Stein.
YouTubeVideo('1j_HxD4iLn8')
Using the nascent video capabilities of modern browsers, you may also be able to display local videos. At the moment this doesn't work very well in all browsers, so it may or may not work for you; we will continue testing this and looking for ways to make it more robust.
The following cell plays a local file called wildlife.mp4 using the HTML5 video tag. This might not work on older browsers (tested with Firefox 43).
HTML("""
<video width="320" height="240" controls>
<source src="../data/wildlife.mp4" type="video/mp4">
</video>
""")
Python objects can declare HTML representations that will be displayed in the Notebook. If you have some HTML you want to display, simply use the HTML class.
s = """<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>"""
h = HTML(s)
h
Header 1 | Header 2 |
---|---|
row 1, cell 1 | row 1, cell 2 |
row 2, cell 1 | row 2, cell 2 |
Here is a small amount of stock data for APPL, written to a file using the magic file
:
%%file data.csv
Date,Open,High,Low,Close,Volume,Adj Close
2012-06-01,569.16,590.00,548.50,584.00,14077000,581.50
2012-05-01,584.90,596.76,522.18,577.73,18827900,575.26
2012-04-02,601.83,644.00,555.00,583.98,28759100,581.48
2012-03-01,548.17,621.45,516.22,599.55,26486000,596.99
2012-02-01,458.41,547.61,453.98,542.44,22001000,540.12
2012-01-03,409.40,458.24,409.00,456.48,12949100,454.53
Writing data.csv
Pandas makes use of this capability to allow DataFrames to be represented as HTML tables.
Read this as into a DataFrame
(we'll talk more about Pandas in a different session):
import pandas as pd
df = pd.read_csv('data.csv')
By default, DataFrames will be represented as HTML:
df
Date | Open | High | Low | Close | Volume | Adj Close | |
---|---|---|---|---|---|---|---|
0 | 2012-06-01 | 569.16 | 590.00 | 548.50 | 584.00 | 14077000 | 581.50 |
1 | 2012-05-01 | 584.90 | 596.76 | 522.18 | 577.73 | 18827900 | 575.26 |
2 | 2012-04-02 | 601.83 | 644.00 | 555.00 | 583.98 | 28759100 | 581.48 |
3 | 2012-03-01 | 548.17 | 621.45 | 516.22 | 599.55 | 26486000 | 596.99 |
4 | 2012-02-01 | 458.41 | 547.61 | 453.98 | 542.44 | 22001000 | 540.12 |
5 | 2012-01-03 | 409.40 | 458.24 | 409.00 | 456.48 | 12949100 | 454.53 |
If we use the print
function we will get the text representation:
print(df)
Date Open High Low Close Volume Adj Close 0 2012-06-01 569.16 590.00 548.50 584.00 14077000 581.50 1 2012-05-01 584.90 596.76 522.18 577.73 18827900 575.26 2 2012-04-02 601.83 644.00 555.00 583.98 28759100 581.48 3 2012-03-01 548.17 621.45 516.22 599.55 26486000 596.99 4 2012-02-01 458.41 547.61 453.98 542.44 22001000 540.12 5 2012-01-03 409.40 458.24 409.00 456.48 12949100 454.53
You can even embed an entire page from another site in an iframe; for example this is today's Wikipedia page for mobile users:
from IPython.display import HTML
HTML('<iframe src=http://wikipedia.org width=700 height=350></iframe>')
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
With the Latex class, you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray:
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}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
Or you can enter latex directly with the %%latex cell magic:
%%latex
\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}
You can integrate your objects with IPython's display system by defining a _repr_html_
method.
The method should return a string of HTML code which the notebook will render as HTML.
For example, a class that contains a URL and a name for it, can be represented as text or as HTML:
class URL:
def __init__(self, url, name=None):
self.url = url
self.name = name or url
def __repr__(self):
return 'Name: {1}, URL: {0}'.format(self.url, self.name)
def _repr_html_(self):
return '<a href="{0}">{1}</a>'.format(self.url, self.name)
url = URL("http://python.yoavram.com", "Yoav Ram </> Python Training")
print(url)
url
Name: Yoav Ram </> Python Training, URL: http://python.yoavram.com
This notebook was written by Yoav Ram and is part of the Python for Engineers course.
The notebook was written using Python 3.6.1. Dependencies listed in environment.yml, full versions in environment_full.yml.
This work is licensed under a CC BY-NC-SA 4.0 International License.