I'm writing python classes for use in Jupyter Notebook that should have pretty representations. For this, I define _repr_html_
methods (that can embed graphics generated on-the-fly by matplotlib
). But sometimes I want to include math as well. For example,
import pandas as pd
import IPython.display as idisp
class FooHtml:
def __init__(self):
self.df = pd.DataFrame({'alpha': [1.0, 2, 3], 'beta': [0.1, 0.2, 0.3]})
def _repr_html_(self):
math = idisp.Math(r'\alpha = \int f(\tau)\,d\tau')
return (
'<h3>FooHtml</h3>'
f'{self.df._repr_html_()}<br>\n'
f'Explanation: {math}, where tau is the time.'
)
FooHtml()
This cell input will generate the following output:
This doesn't show the math, although display(math)
does show an equation:
The non-rendering is because str(math) == '<IPython.core.display ...>'
will be interpreted as an invalid HTML tag. The question is: how do I actually render math embedded in a HTML representation. I figured out the answer, which I couldn't find anywhere; which I'll post as an answer.