Rendering LaTeX in output cells in Colaboratory

2019-02-19 21:28发布

I expect a cell like

from IPython.display import display, Math
display(Math(r"e^\alpha"))

to render with MathJax as it does in normal jupyter, but instead it just displays latex code like:

$$e^\alpha$$

Is there a way to get Colaboratory to render it correctly? (It manages it fine for text cells).

4条回答
手持菜刀,她持情操
2楼-- · 2019-02-19 21:51

I am not sure that it's the right method,but it works:

from IPython.display import Javascript, Math
display(Javascript("var sc = document.createElement('script')"))
display(Javascript("sc.type='text/javascript'; sc.src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/MathJax.js?config=TeX-AMS-MML_HTMLorMML&dummy=.js'"))
display(Javascript("var currentDiv = document.activeElement.parent"))
#display(Javascript("sc.onload = function () {console.log('loaded')};"))
display(Javascript("document.body.insertBefore(sc, currentDiv)"))
display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx'))
display(Math(r"e^\alpha"))
查看更多
霸刀☆藐视天下
3楼-- · 2019-02-19 21:55

First you question is uncorrect, it should be "inline" not output in colaboratory.

Second to answer your question, just change "Code" option in menu bar to "Markdown" and executive $= e^\alpha$ or $$= e^\alpha$$ in "In box".

This is example colab show latex in mardown

Update: Sorry for my late update, i saw in colaboratory notebook so difference , to show LaTeX in it, just Insert "text cell" in Insert menu bar and executive $$= e^\alpha$$ or $= e^\alpha$ in input box

查看更多
够拽才男人
4楼-- · 2019-02-19 22:04

Simplify scraaappy's answer a bit.

from IPython.display import HTML, Math
display(HTML("<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/"
             "latest.js?config=default'></script>"))
Math(r"e^\alpha")

It just includes MathJax library so the following equations can be displayed.

Or use the built-in output._publish (Aug 2018)

from IPython.display import Math
from google.colab.output._publish import javascript
url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=default"

javascript(url=url)
Math(r"e^\alpha")

Instead of CDN, you can also use MathJax that comes with Colab. https://colab.research.google.com/static/mathjax/MathJax.js?config=default

查看更多
一纸荒年 Trace。
5楼-- · 2019-02-19 22:10

As a temporary workaround, you can define your own equation rendering function:

from IPython.display import HTML, Math
def mview(e):
  display(HTML("<script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/"
         "latest.js?config=default'></script>"))
  return Math(latex(e))

And then use it as follows:

e = Integral(cos(x)**2, (x, 0, pi))
mview(e)
查看更多
登录 后发表回答