2

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"$ \begin{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

Community
  • 1
  • 1
tobias47n9e
  • 2,233
  • 3
  • 28
  • 54

1 Answers1

4

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"$ \begin{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"$ \begin{matrix} a & b & c \\ d & e & f \\ g & h & i \end{matrix} $",
    (0.25, 0.25),
    textcoords='axes fraction', size=20)
farenorth
  • 10,165
  • 2
  • 39
  • 45
  • 2
    It seems like there is a bug in the current 1.5 build of matplotlib, because I can't get either of the two solutions to work. – tobias47n9e Oct 13 '14 at 09:17
  • 2
    Do you have LaTeX installed on your system? – farenorth Oct 13 '14 at 15:57
  • I have no idea how you guessed that, but you are right. I edited the question to what solved the problem. I am now using your first suggestion which looks exactly like what I wanted to do. Thank you again! – tobias47n9e Oct 13 '14 at 17:28