How to programmatically generate markdown output in Jupyter notebooks?

Question:

I want to write a report for classes in Jupyter notebook. I’d like to count some stuff, generate some results and include them in markdown. Can I set the output of the cell to be interpreted as markdown?
I’d like such command: print '$phi$' to generate phi symbol, just like in markdown.
In other words, I’d like to have a template made in markdown and insert the values generated by the program written in the notebook. Recalculating the notebook should generate new results and new markdown with those new values inserted. Is that possible with this software, or do I need to replace the values by myself?

Asked By: fulaphex

||

Answers:

The functions you want are in the IPython.display module.

from IPython.display import display, Markdown, Latex
display(Markdown('*some markdown* $phi$'))
# If you particularly want to display maths, this is more direct:
display(Latex('phi'))
Answered By: Thomas K

You are basically asking for two different things:

  1. Markdown cells outputting code results.

    I’d like to count some stuff, generate some results and include them in markdown. […] I’d like to have a template in markdown and insert values generated by the program in the notebook

  2. Code cells outputting markdown

    I’d like such command: print '$phi$' to generate phi symbol, just like in markdown.

Since 2. is already covered by another answer (basically: use Latex() or Markdown() imported from IPython.display), I will focus on the first one:


1. Markdown Template with inserted variables

With the Jupyter extension Python Markdown it actually is possible to do exactly what you describe.

Installation instructions can be found on the github page of nbextensions. Make sure you’ll enable the python markdown extension using a jupyter command or the extension configurator.

With the extension, variables are accessed via {{var-name}}. An example for such a markdown template could look like this:

Python Code in Markdown Cells

The variable a is {{a}}

You can also embed LateX: {{b}} in here!

Even images can be embedded: {{i}}

Naturally all variables or images a, b, i should be set in previous code. And of course you may also make use of Markdown-Latex-style expressions (like $phi$) without the print command. This image is from the wiki of the extension, demonstrating the capability.

example from wiki


Further info on this functionality being integrated into ipython/jupyter is discussed in the issue trackers for ipython and jupyter.

Answered By: Honeybear

As an addition to Thomas’s answer. Another easier way to render markdown markup is to use display_markdown function from IPython.display module:

from IPython.display import display_markdown

display_markdown('''## heading
- ordered
- list

The table below:

| id |value|
|:---|----:|
| a  |  1  |
| b  |  2  |
''', raw=True)

Output below:

enter image description here

Usage example could be found on Google Colab Notebook

Answered By: feeeper

Another option is to use Rich for Markdown rendering and UnicodeIt for symbols. It has some limitations, as Rich uses CommonMark, which does not support tables, for example. Rich has other ways to render tables though; this is detailed in the documentation.

Here is an example:

from rich.markdown import Markdown
import unicodeit

alpha = unicodeit.replace('\alpha')
epsilon = unicodeit.replace('\epsilon')
phi = unicodeit.replace('\phi')

MARKDOWN = f"""
# This is an h1

Rich can do a pretty *decent* job of rendering markdown.

1. This is a list item
2. This is another list item

## This is an h2

List of **symbols**:

- alpha: {alpha}
- epsilon: {epsilon}
- phi: {phi}

This is a `code` snippet:

```py
# Hello world
print('Hello world')
```

This is a blockquote:

> Rich uses [CommonMark](https://commonmark.org/) to parse Markdown.

---

### This is an h3

See [Rich](https://github.com/Textualize/rich) and [UnicodeIt](https://github.com/svenkreiss/unicodeit) for more information.
"""

Markdown(MARKDOWN)

… which produces the following output:

Rich + UnicodeIt output

Answered By: nms
from tabulate import tabulate
from IPython.display import Markdown
A2 = {
    'Variable':['Bundle Diameter','Shell Diameter','Shell Side Cross Flow area','Volumetric Flowrate','Shell Side Velocity'],
    'Result':[3.4, 34, 78.23, 1.0 ,  2.0],
    'Unit' : ['$in$', '$in$', '$ft^2$', '$ft^{3}s^{-1}$', '$fts^{-1}$']}
temp_html=tabulate(A2, headers='keys', tablefmt='html')
Markdown(temp_html.replace('<table>','<table style="width:50%">'))

.replace() usage will not break latex code & avoid column(s) overstrech. This way one can dynamically generate tables with Latex

Answered By: nightcrawler

One more option. There is an open-source framework for converting Jupyter notebooks to web apps. It is called Mercury. It has function called Markdown to display any string as Markdown. Here is a documentation.

Below is an example notebook that dynamically displays Markdown:

import mercury as mr
slider = mr.Slider(label="Favorite number", value=5)
name = "Piotr"
mr.Markdown(f"""# Hello {name}

## Your variable is {slider.value}
""")

notebook with markdown

Notebook and web app created with Mercury. It has dynamic Markdown:
notebook and app with markdown

Answered By: pplonski

There is an interesting lab extension called jupyterlab-myst which will swap the standard markdown renderer in the notebook out for the mystjs renderer.

This means you can render more than standard commonmark markdown in markdown cells including being able to interpolate variable values directly into markdown. These can be simple variables, images, cell outputs and even ipywidgets.

This opens up a lot more possibilities on how you can interlace results from computation in code cells with markdown content in the notebooks. When a notebook is re-executed the interpolated values in the markdown will be updated.

There are other features that are helpful for report writing that could also help with the OP’s use case.

Example of ipywidgets rendered in a markdown cell

Answered By: stevejpurves