How to display a matrix in the Matplotlib annotations

后端 未结 1 1941
说谎
说谎 2020-12-06 23:32

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:

相关标签:
1条回答
  • 2020-12-07 00:19

    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)
    
    0 讨论(0)
提交回复
热议问题