'How to write math symbols in plotly dash app?

I want to plot math symbols in a plotly dash app.

For example, I've Tried this:

import dash
import dash_html_components as html

app = dash.Dash(__name__)
app.layout = html.Div(
    children=[
        html.P(r'$ Area (m^{2}) $'),
        dcc.Markdown(r'$ Area (m^{2}) $')
    ]
)
app.run_server()

and this was the result:

result

How can I get these result?

enter image description here



Solution 1:[1]

You can try Mathjax. The following works at my end (Python 3.9.1, dash==1.19.0, dash-html-components==1.1.2)

First create a javascript file (anyname.js) in the assets folder of your current project. In that file have just the following line:

setInterval("MathJax.Hub.Queue(['Typeset',MathJax.Hub])",1000);

Then back to your python file:

from dash import Dash
import dash_html_components as html

MATHJAX_CDN = '''
https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/
MathJax.js?config=TeX-MML-AM_CHTML'''

external_scripts = [
                    {'type': 'text/javascript',
                     'id': 'MathJax-script',
                     'src': MATHJAX_CDN,
                     },
                    ]


app = Dash(__name__, external_scripts=external_scripts)
app.layout = html.Div(
    children=[
        html.P('''\(Area\)(\(m^2\)) '''),
    ]
)
app.run_server()

Some caveats:

  • I have never been able to get Mathjax to work in the Markdown component.
  • This solution doesn't work with the latest Mathjax version (nor with 2.7.7). I am unsure which is the latest version it will work with.

If you are able to address any of the two caveats do let me know.

Solution 2:[2]

MathJax 3 works in Dash v2.3.0 which includes Plotly.js v2.10.0 with Markdown. Example: dcc.Markdown('$$y=x+1$$', mathjax=True)

Solution 3:[3]

With plotly you have to use unicode. For example if you want to print a greek letter mu is "\u03bc". You can obtain some symbols from here and superscripts from here. m square will be "m\U+2072".

Solution 4:[4]

Install

pip install dash -U

Code

import dash
from dash import dcc, html

app = dash.Dash()
app.layout = html.Div([
    dcc.Markdown('$Area (m^{2})$', mathjax=True),
])
app.run_server()

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman
Solution 2 Warren Van Wyck
Solution 3 Francisco Iaconis
Solution 4 XerCis