LaTeX in JavaScript

How to add LaTeX to javascript D3.js-based graphs.


Plotly Studio: Transform any dataset into an interactive data application in minutes with AI. Try Plotly Studio now.

Plotly.js renders LaTeX in titles, axis labels, annotations, and legend entries when MathJax is loaded on the page. Wrap the expression in $ delimiters, as in the example below.

Plotly.js v4 supports MathJax v3 and v4, and uses the tex-svg component. Load one of the following before plotly.js:

<!-- MathJax v3 -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js"></script>
<!-- or MathJax v4 -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@4/tex-svg.js"></script>

MathJax v2 is no longer supported. If your page loads MathJax.js?config=TeX-MML-AM_CHTML, replace it with one of the tags above — the ?config= query string is not used from MathJax v3 onward, since the component is selected by the file you load.

// remember to load MathJax v3 or v4 (tex-svg.js) - see https://plotly.com/javascript/LaTeX/
var trace1 = {
  x: [1, 2, 3, 4],
  y: [1, 4, 9, 16],
  name: '$\\alpha_{1c} = 352 \\pm 11 \\text{ km s}^{-1}$',
  type: 'scatter'
};
var trace2 = {
  x: [1, 2, 3, 4],
  y: [0.5, 2, 4.5, 8],
  name: '$\\beta_{1c} = 25 \\pm 11 \\text{ km s}^{-1}$',
  type: 'scatter'
};
var data = [trace1, trace2];
var layout = {
  xaxis: {
    title: {
      text: '$\\sqrt{(n_\\text{c}(t|{T_\\text{early}}))}$'
    }
  },
  yaxis: {
    title: {
      text: '$d, r \\text{ (solar radius)}$'
    }
  }
};
Plotly.newPlot('myDiv', data, layout);