【问题标题】:How to display a matrix in the Matplotlib annotations如何在 Matplotlib 注释中显示矩阵
【发布时间】:2014-10-12 19:37:31
【问题描述】:

我正在尝试使用 Matplotlib-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)

编辑:

问题的一部分是我缺少包含“type1cm”的“texlive-latex-extra”,这是正确渲染它所必需的。另见:Python: Unable to Render Tex in Matplotlib

【问题讨论】:

    标签: matplotlib


    【解决方案1】:

    MatPlotLib 使用自己的排版框架 (MathText)。您的系统的 LaTeX 渲染可以通过 rcParams['text.usetex'] = True 启用。

    您遇到的另一个问题是双引号多行字符串。如果不使用\,这实际上是不允许的,而且您现有的\\ 很难管理。

    试试这个:

    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)
    

    这里我使用了array 环境,而不是matrix,因为我不认为后者是LaTeX 内置的。如果你真的想要matrix——或其他 amsmath 项目——你可以将 amsmath 包添加到 MatPlotLib LaTeX 序言中:

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

    那么matrix 环境就可以工作了,

    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)
    

    【讨论】:

    • 目前 matplotlib 的 1.5 版本中似乎存在一个错误,因为我无法让这两种解决方案中的任何一种工作。
    • 你的系统上安装了 LaTeX 吗?
    • 我不知道你是怎么猜到的,但你是对的。我将问题编辑为解决问题的方法。我现在正在使用您的第一个建议,它看起来与我想要做的完全一样。再次感谢您!
    猜你喜欢
    • 2016-07-23
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多