+1 vote
in Programming Languages by (89.5k points)
I am using Python library matplotlib for generating a plot where I need to write some mathematical equations as x and y labels. Is there any way to put the latex code in the matplotlib so that it renders the beautiful equation?

E.g. x/N should be shown as output of \frac{x}{N}.

1 Answer

+2 votes
by (364k points)
selected by
 
Best answer

Matplotlib supports LaTeX-like syntax in its labels using raw strings with dollar signs ($) to indicate math mode. Here’s how you can do it for your specific case:

plt.xlabel(r"$\frac{x}{N}$")

Always use a raw string (r"...") to avoid Python interpreting backslashes, and surround the LaTeX expression with $...$ so matplotlib renders it in math mode.

Here is another example:

plt.ylabel(r"$\hat{p}_2^{(x)} - \hat{p}_2$") 


...