Use Latex In Jupyter Notebook

Posted on  by admin

Jupyter notebook tutorial on how to install, run, and use Jupyter for interactive matplotlib plotting, data analysis, and publishing code. This extension for Jupyter notebook enables the use of some LaTeX commands and environments markdown cells. LaTeX commands and environments support for some LaTeX commands within markdown cells, e.g. Textit, textbf, underline. Support for theorems-like environments, support for labels and cross references.

Jupyter notebook tutorial on how to install, run, and use Jupyter for interactive matplotlib plotting, data analysis, and publishing code


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Introduction¶

Jupyter has a beautiful notebook that lets you write and execute code, analyze data, embed content, and share reproducible work. Jupyter Notebook (previously referred to as IPython Notebook) allows you to easily share your code, data, plots, and explanation in a sinle notebook. Publishing is flexible: PDF, HTML, ipynb, dashboards, slides, and more. Code cells are based on an input and output format. For example:

Installation¶

There are a few ways to use a Jupyter Notebook:

  • Install with pip. Open a terminal and type: $ pip install jupyter.
  • Windows users can install with setuptools.
  • Anaconda and Enthought allow you to download a desktop version of Jupyter Notebook.
  • nteract allows users to work in a notebook enviornment via a desktop application.
  • Microsoft Azure provides hosted access to Jupyter Notebooks.
  • Domino Data Lab offers web-based Notebooks.
  • tmpnb launches a temporary online Notebook for individual users.

Getting Started¶

Once you've installed the Notebook, you start from your terminal by calling $ jupyter notebook. This will open a browser on a localhost to the URL of your Notebooks, by default http://127.0.0.1:8888. Windows users need to open up their Command Prompt. You'll see a dashboard with all your Notebooks. You can launch your Notebooks from there. The Notebook has the advantage of looking the same when you're coding and publishing. You just have all the options to move code, run cells, change kernels, and use Markdown when you're running a NB.

Helpful Commands¶

- Tab Completion: Jupyter supports tab completion! You can type object_name.<TAB> to view an object’s attributes. For tips on cell magics, running Notebooks, and exploring objects, check out the Jupyter docs.
- Help: provides an introduction and overview of features.

- Quick Reference: open quick reference by running:

- Keyboard Shortcuts:Shift-Enter will run a cell, Ctrl-Enter will run a cell in-place, Alt-Enter will run a cell and insert another below. See more shortcuts here.

Languages¶

The bulk of this tutorial discusses executing python code in Jupyter notebooks. You can also use Jupyter notebooks to execute R code. Skip down to the [R section] for more information on using IRkernel with Jupyter notebooks and graphing examples.

Package Management¶

When installing packages in Jupyter, you either need to install the package in your actual shell, or run the ! prefix, e.g.:

You may want to reload submodules if you've edited the code in one. IPython comes with automatic reloading magic. You can reload all changed modules before executing a new line.

Some useful packages that we'll use in this tutorial include:

  • Pandas: import data via a url and create a dataframe to easily handle data for analysis and graphing. See examples of using Pandas here: https://plotly.com/pandas/.
  • NumPy: a package for scientific computing with tools for algebra, random number generation, integrating with databases, and managing data. See examples of using NumPy here: https://plotly.com/numpy/.
  • SciPy: a Python-based ecosystem of packages for math, science, and engineering.
  • Plotly: a graphing library for making interactive, publication-quality graphs. See examples of statistic, scientific, 3D charts, and more here: https://plotly.com/python.

Import Data¶

You can use pandas read_csv() function to import data. In the example below, we import a csv hosted on github and display it in a table using Plotly:

Use dataframe.column_title to index the dataframe:

Most pandas functions also work on an entire dataframe. For example, calling std() calculates the standard deviation for each column.

Plotting Inline¶

You can use Plotly's python API to plot inside your Jupyter Notebook by calling plotly.plotly.iplot() or plotly.offline.iplot() if working offline. Plotting in the notebook gives you the advantage of keeping your data analysis and plots in one place. Now we can do a bit of interactive plotting. Head to the Plotly getting started page to learn how to set your credentials. Calling the plot with iplot automaticallly generates an interactive version of the plot inside the Notebook in an iframe. See below:

Plotting multiple traces and styling the chart with custom colors and titles is simple with Plotly syntax. Additionally, you can control the privacy with sharing set to public, private, or secret.

Now we have interactive charts displayed in our notebook. Hover on the chart to see the values for each bar, click and drag to zoom into a specific section or click on the legend to hide/show a trace.

Plotting Interactive Maps¶

Plotly is now integrated with Mapbox. In this example we'll plot lattitude and longitude data of nuclear waste sites. To plot on Mapbox maps with Plotly you'll need a Mapbox account and a Mapbox Access Token which you can add to your Plotly settings.

3D Plotting¶

Using Numpy and Plotly, we can make interactive 3D plots in the Notebook as well.

Animated Plots¶

Checkout Plotly's animation documentation to see how to create animated plots inline in Jupyter notebooks like the Gapminder plot displayed below:

Plot Controls & IPython widgets¶

Add sliders, buttons, and dropdowns to your inline chart:

Additionally, IPython widgets allow you to add sliders, widgets, search boxes, and more to your Notebook. See the widget docs for more information. For others to be able to access your work, they'll need IPython. Or, you can use a cloud-based NB option so others can run your work.

Executing R Code¶

IRkernel, an R kernel for Jupyter, allows you to write and execute R code in a Jupyter notebook. Checkout the IRkernel documentation for some simple installation instructions. Once IRkernel is installed, open a Jupyter Notebook by calling $ jupyter notebook and use the New dropdown to select an R notebook.

See a full R example Jupyter Notebook here: https://plotly.com/~chelsea_lyn/14069

Additional Embed Features¶

We've seen how to embed Plotly tables and charts as iframes in the notebook, with IPython.display we can embed additional features, such a videos. For example, from YouTube:

LaTeX¶

We can embed LaTeX inside a Notebook by putting a $$ around our math, then run the cell as a Markdown cell. For example, the cell below is $$c = sqrt{a^2 + b^2}$$, but the Notebook renders the expression.

Or, you can display output from Python, as seen here.

$displaystyle F(k) = int_{-infty}^{infty} f(x) e^{2pi i k} dx$

Exporting & Publishing Notebooks¶

We can export the Notebook as an HTML, PDF, .py, .ipynb, Markdown, and reST file. You can also turn your NB into a slideshow. You can publish Jupyter Notebooks on Plotly. Simply visit plot.ly and select the + Create button in the upper right hand corner. Select Notebook and upload your Jupyter notebook (.ipynb) file!The notebooks that you upload will be stored in your Plotly organize folder and hosted at a unique link to make sharing quick and easy.See some example notebooks:

Publishing Dashboards¶

Users publishing interactive graphs can also use Plotly's dashboarding tool to arrange plots with a drag and drop interface. These dashboards can be published, embedded, and shared.

Publishing Dash Apps¶

For users looking to ship and productionize Python apps, dash is an assemblage of Flask, Socketio, Jinja, Plotly and boiler plate CSS and JS for easily creating data visualization web-apps with your Python data analysis backend.

Jupyter Gallery¶

For more Jupyter tutorials, checkout Plotly's python documentation: all documentation is written in jupyter notebooks that you can download and run yourself or checkout these user submitted examples!

Last edited: March 6th, 2018

A short introduction to the use of Jupyter Notebook

In this tutorial we introduce the web-based application Jupyter Notebook. It is ment as a quick and easy introduction to the use of the application. For a full guide on every function, check out the Jupyter Notebook homepage. It is assumed that the reader is already familiar with Python. See e.g. the notebooks on Basic Plotting or Introduction to Matplotlib for a general discussion on plotting. For an alternate introduction by Erik André Jakobsen in norwegian, click here.

What is Jupyter Notebook?

Much more than only Python!Jupyter Notebook is an web-based application suitible for the process of solving a computational problem and presenting the results along with code, explanatory text and background. Jupyter Notebook combines two components:

The web application: a browser-based tool for interactive authoring of documents which combine explanatory text, mathematics, computations and their rich media output.

Notebook documents: a representation of all content visible in the web application, including inputs and outputs of the computations, explanatory text, mathematics, images, and rich media representations of objects.

Why Jupyter Notebook?

  • Can be loaded from github and nbviewer.
  • Open source.
  • Code, theory and results fits neatly side by side.
  • Can run selected code cells from browser, with the corresponding results attached to the code wich generate them.
  • Don't need to import data and packages for every run.
  • In-browser text editing using Markdown markup language.
  • Easy to write mathematical notation with markdown cells using LaTeX.
  • Rich media representation of objects e.g. image customizing using HTML and CSS.

Installation

Do you have Python installed?

You need Python to run the IPython Notebook on your system. To see if you have it installed, type the following into the command line:

NotebookNotebook

python.

If you get a response similar to this

you're good. If not, see below. You might have to type python3 to get Python 3 if you launch Python 2 by default.

Latex Equations In Jupyter Notebook

Installing the Notebook

Jupyter's own installation guide is a good place to start. They explain how to install the notebook using either Anaconda or pip.

Starting a Notebook

When you have the application installed, creating a notebook is easy. The fastest way is by using terminal/CMD. Executing the commandjupyter notebookfrom the command line will start the notebook server and open a web browser to the web application dashboard. The command will also print some information about the notebook server in your console. When you connect for the first time you may have to copy and paste the URL presented in the console into your browser to open the application dashboard.

If you have Anaconda installed, you may open Jupyter Notebook by launching it from Anaconda-Navigator, which is an default application from Anaconda.

Write Latex In Jupyter Notebook

From the Jupyter Notebook browser dashboard you can navigate through your own directories and open existing notebooks or create new ones by clicking the New-button and selecting Notebook: Python 3. This will open a new tab in your browser and you are good to go! You can also drag and drop .ipynb notebooks and standard .py Python source code files into the notebook list area.

Gif credit: Jupyter Notebook

Alternatively, you can open a particular notebook directly from the command line with the command jupyter notebook my_notebook.ipynb. Be sure to be in the same directory as the notebook file.

Notebook user interface and structure

Structure of a Notebook

Before desscribing the interface you should now a bit about the structure of a Jupyter Notebook.The notebook basically consists of a sequence of cells aranged unnderneath eachother. Usually a mixture of Markdown cells and code cells. As default, one code cell is presented. Here you can write python code with automatic syntax highlighting, indention, and tab completion/introspection. The code can be executed by using Shift-Enter and the eventual computation result will be display under the cell. Also a new code cell will be added. This new cell can then be changed to e.g. a markdown cell if you want to comment the result in rich text. Next, you can create a new code cell and do more computation without having to run the previous code cells.

Interface

The interface of a new notebook presents a notebook name, a menu bar, a toolbar and an empty default code cell.

From the menu bar you can open, copy and create new notebooks, print and download a preview, insert, delete manipulate and run cells (wich is the core of the notebook structure), and more.

The toolbar is a quick and easy accsess way of navigating through and working with cells. As well as changing cell types.

The notebook name can be altered directly by clicking on the title.

Cells

A cell is a multiline text input field, and its contents can be executed by using Shift-Enter. Jupyter Notebook has three types of cells: code cells, markdown cells and raw cells.

Code cells Allows you to write and edit code in Python. Other languages such as R or Julia can be handled using cell magic commands. The only magic command we will present in this tutorial is the command %matplotlib inline, demostrated under Plotting.

Markdown cells. If you want to document your computation, let's say you are writing a report and need an introduction, theory section with mathematical equation and a coclusion to accompony your code, then you want to use a markdown cell.

Using the Markdown language, this cell makes an easy way of writing and performing text markup (italic and bold text, lists, headings, etc.). A great thing about Markdown is that you can include mathematics and equations in a straightforward way, using standard LaTeX notation.

Additionally, Markdown allows arbitrary HTML code for formatting. Wich makes it possible to customize images and e.g make HTML lists.

As an example of the Markdown language:

Use latex in jupiter notebook download

Executing the code above will yield:

For a full cheatsheat of all Markdown language funcionalities, click here.

What is jupyter notebook

Raw cells provide a place in wich you can write output directly. Raw cells are not evaluated by the notebook. This means that you can write LaTeX code in a raw cell, but it will not be rendered until you convert and view the notebook through a preview application, such as nbviewer.

However, this enables the possibility of defining your own style and font of the notebook using CSS or HTML in a raw cell. More on this later

Edit mode and command mode

While navigating through cells in the notebook you are woking in either command or edit mode, indentfied by the color of the frame around the cell. Blue or green left marrow and frame colour respectively corresponds to command or edit mode.

In command mode you can easy navigate through the cells using the arrow keys. You can also change the cell type of the selected sell with keyboard shortcuts. Typing M will change it to a markdown cell and Y will change it to a code cell. Pressing Hwill show all available keyboard shortcuts, both in command and edit mode.

While in command mode, you can enter edit mode by hitting Enter. This will allow you to edit the content of the current cell. To return to command mode, press esc.

Commanding Shift+Enter will run the selected cell in both command and edit mode. As well as moving to the next cell, or create a new code cell if necesarry. To run without leaving the cell, press Ctrl+Enter.

Plotting

To embed plots within the notebook (this is often default behaviour), one needs to use the inline backend by typing

To change backend, one can use

This enables amongst other plotting in a seperate window.

Extensions

More advanced users can note that there exists some extensions to Jupyter Notebook, such as Jupyter Nbextensions Configurator and Jupyter notebook extensions. The jupyter_nbextensions_configurator jupyter server extension provides graphical user interfaces for configuring which nbextensions are enabled. The jupyter_contrib_nbextensions repository contains a collection of extensions that add functionality to the Jupyter notebook. This includes equation labels (this is now also included at NBviewer and when downloading the notebook as HTML), codefolding, spell checking and much more.

Sharing your Notebook

There are a number of ways to view and share your finished notebook. A Jupyter Notebook is by default a .ipynb file. This filetype can be shared and opened by anyone having Jupyter Notebook installed. To open an .ipynb, proceed as instructed above.

From File in the menu bar you can print a preview or download the notebook in a variaty of filetypes. If you wish to download it as a .pdf, LaTeX and pandoc is required.

However, a better way of displaying your notebook is by using nbviewer.

  1. Upload your .ipynb notebook to a webpage, e.g your own homepage at NTNU (folk.ntnu.no).
  2. Enter the location of your Jupyter Notebook (URL) to the nbviewer homepage and click Go!. This will redirect you to the rendered nbviewer web page for your notebook.
Jupyter display latex

Now you can copy the URL of the notebook-page and share it as you like. This link will be functional as long as your notebook .ipynb-file is located at your chosen web page.

For an instruction on how to create and upload files to your homepage folk.ntnu.no/brukernavn, click here.