Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

How to display a matrix in the Matplotlib annotations

I'm trying to plot a matrix using the annotations of a Matplotlib-Plot. Is this even possible?

Tried around with the most basic example, which all break the plot:

ax.annotate(r"$ egin{matrix} a & b & c \
              d & e & f \ 
              g & h & i end{matrix} $", (0.25, 0.25),
              textcoords='axes fraction', size=20)

Edit:

Part of the problem was that I was missing "texlive-latex-extra" which contains "type1cm", which is needed to render this correctly. See also: Python: Unable to Render Tex in Matplotlib

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

MatPlotLib uses its own typesetting framework (MathText). Your system's LaTeX rendering can be enabled by, rcParams['text.usetex'] = True.

The other problem that you have is a double-quoted multi-line string. This isn't really allowed without using a , and that is difficult to manage with your existing \.

Try this:

from matplotlib import rcParams

rcParams['text.usetex'] = True

ax.annotate(
    r"$ egin{array}{ccc} a & b & c \ d & e & f \ g & h & i end{array} $",
    (0.25, 0.25),
    textcoords='axes fraction', size=20)

Here I have used the array environment, rather than matrix because I don't think the latter is a LaTeX built-in. If you really want matrix--or other amsmath items--you can add the amsmath package to the MatPlotLib LaTeX preamble:

rcParams['text.latex.preamble'] = r'usepackage{amsmath}'

Then the matrix environment will work,

ax.annotate(
    r"$ egin{matrix} a & b & c \ d & e & f \ g & h & i end{matrix} $",
    (0.25, 0.25),
    textcoords='axes fraction', size=20)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...