Using LaTeX/MathJax in labels parameter of px.line

Hello!

I’m trying to use LaTeX or MathJax to display mathematical expressions in the labels dictionary values within the px.line function. However, despite using the r"$...$" syntax and other attempts, the mathematical expressions are not rendered correctly on the plot.

Here’s an example of the code I am using:

import plotly.express as px
import plotly.graph_objects as go

# Example data
df = px.data.gapminder()

# Attempt to use LaTeX in labels
fig = px.line(
    df, 
    x='year', 
    y='gdpPercap', 
    title="GDP Over Time",
    labels={'year': r"$t$", 'gdpPercap': r"$GDP_{pc}$"}
)

fig.show()

I expected the mathematical expressions to appear on the X and Y axes, but instead, plain strings are displayed. I have tried various syntaxes, but it doesn’t work.

Could you please confirm whether LaTeX is supported in the labels parameter? If so, what is the correct way to apply it? Or is there another way to include mathematical expressions in the plot?

Thank you in advance for your help!

1 Like

Hey @samodurOFF, did you install the library?

Figure titles, axis labels and annotations all accept LaTeX directives for rendering mathematical formulas and notation, when the entire label is surrounded by dollar signs $...$. This rendering is handled by the MathJax library (version 2.7.5), which must be loaded in the environment where figures are being rendered. MathJax is included by default in Jupyter-like environments, and LateX directives work with Jupyter Notebook version 6. LaTeX directives do not work with Jupyter Notebook version 7. When embedding Plotly figures in other contexts it may be required to ensure that MathJax is separately loaded, for example via a <script> tag pointing to a content-delivery network (CDN).

2 Likes