在 Matplotlib 中使用 Latex 绘制标题/轴标签

在 Matplotlib 中使用 Latex 绘制标题/轴标签

抱歉,如果这是转帖;我相信这个问题经常被问到,但我在搜索中找不到我想要的确切内容。我正在尝试编写一个科学绘图程序matplotlib(使用 python 2.7)我无法让它按照我期望的方式识别 LaTeX 代码。

在 matplotlib 网站上,有一个可以在我的机器(Ubuntu 12.04)上完美运行的示例:

    from matplotlib import rc
from numpy import arange, cos, pi
from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, \
     grid, savefig, show


rc('text', usetex=True)
rc('font', family='serif')
figure(1, figsize=(6,4))
ax = axes([0.1, 0.1, 0.8, 0.7])
t = arange(0.0, 1.0+0.01, 0.01)
s = cos(2*2*pi*t)+2
plot(t, s)

xlabel(r'\textbf{time (s)}')
ylabel(r'\textit{voltage (mV)}',fontsize=16)
title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
      fontsize=16, color='r')
grid(True)
savefig('tex_demo')


show()

但是当我尝试将这里的概念应用到我现有的代码中时,事情就变得糟糕了。我的代码正在从文本文件中读取值,以用作一系列子图的标题和轴的字符串。文本文件看起来像这样,原始文本中每行只有一个换行符:

示例 \texit{情节标题}

x 标签

y 标签

因此,我希望除了“情节标题”之外,所有内容都是普通的,它应该是斜体。这是我编写的函数:

from matplotlib import rc

...
def plot_graphic(formatting_file):
    rc('text', usetex=True)
    rc('font', family='serif')
    formatting = open(formatting_file)
    data = formatting.readlines()
    title_text = data[0]
    sup_title_size = 20
    title_size = int(0.75*sup_title_size)
    x_axis_label = data[1]
    y_axis_label = data[2]
    plt.subplot(224)
    plt.plot(n.x, o, n.x, s, "r")
    plt.title("Original and Smoothed Data", fontsize=title_size)
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.subplot(221)
    plt.plot(n.x, o)
    plt.title("Original Data", fontsize=title_size)
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.subplot(223)
    plt.plot(n.x, s, "r")
    plt.title("Smoothed Data", fontsize=title_size)
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.subplot(222)
    plt.plot(gx, gy, "k.-")
    plt.title("Smoothing Window", fontsize=title_size)
    plt.xlabel(x_axis_label)
    plt.ylabel("Window Function")
    plt.suptitle(title_text, fontsize=sup_title_size)
    plt.subplots_adjust(wspace=0.3)
    plt.show()
    formatting.close()

其中“formatting_file”是一个字符串(包含上述内容的文件的路径),并且一切工作正常,无需 Tex 格式化尝试(如果我删除以 rc 开头的行)。但是,当我运行此命令时,我得到了一堵回溯,结尾是:

RuntimeError: LaTeX was not able to process the following string:
''
Here is the full report generated by LaTeX: 

This is pdfTeX, Version 3.1415926-1.40.10 (TeX Live 2009/Debian)
entering extended mode
(./65d362bbbe189488f3ed27a3ef3526ff.tex
LaTeX2e <2009/09/24>
Babel <v3.8l> and hyphenation patterns for english, usenglishmax, dumylang, noh
yphenation, loaded.
(/usr/share/texmf-texlive/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texmf-texlive/tex/latex/base/size10.clo))
(/usr/share/texmf-texlive/tex/latex/type1cm/type1cm.sty)
(/usr/share/texmf-texlive/tex/latex/psnfss/helvet.sty
(/usr/share/texmf-texlive/tex/latex/graphics/keyval.sty))
(/usr/share/texmf-texlive/tex/latex/psnfss/courier.sty)
(/usr/share/texmf-texlive/tex/latex/base/textcomp.sty
(/usr/share/texmf-texlive/tex/latex/base/ts1enc.def))
(/usr/share/texmf-texlive/tex/latex/geometry/geometry.sty
(/usr/share/texmf-texlive/tex/generic/oberdiek/ifpdf.sty)
(/usr/share/texmf-texlive/tex/generic/oberdiek/ifvtex.sty)

Package geometry Warning: Over-specification in `h'-direction.
    `width' (5058.9pt) is ignored.


Package geometry Warning: Over-specification in `v'-direction.
    `height' (5058.9pt) is ignored.

) (./65d362bbbe189488f3ed27a3ef3526ff.aux)
(/usr/share/texmf-texlive/tex/latex/base/ts1cmr.fd)
(/usr/share/texmf-texlive/tex/latex/psnfss/ot1pnc.fd)
*geometry auto-detecting driver*
*geometry detected driver: dvips*
(./65d362bbbe189488f3ed27a3ef3526ff.aux) )
No pages of output.
Transcript written on 65d362bbbe189488f3ed27a3ef3526ff.log.

归根结底,我对 LaTeX 的使用经验不多,但我正在努力学习,所以我不明白这些错误。我不明白为什么我的代码不起作用,它似乎与示例没有太大区别。作为参考,我也在 x86 Windows 7 机器上尝试过,结果相同。

我错过了什么?


编辑:

我认为我为示例提供的代码片段太长了。更短、更简单的版本如下:

import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
rc('font', family='serif')

data = ["Example \texit{plot title}\n", "x label", "y label"]
title_text = data[0]
x_axis_label = data[1]
y_axis_label = data[2]

plt.plot([1,2,3,4],[1,2,3,4])
plt.title(title_text)
plt.xlabel(x_axis_label)
plt.ylabel(y_axis_label)
plt.show()

答案1

我认为您的问题是从文件中读取的换行符。尝试使用 删除它们rstrip()。这将修复您的简短示例。对于您的较长代码,可能如下所示:

title_text = data[0].rstrip('\r\n')
sup_title_size = 20
title_size = int(0.75*sup_title_size)
x_axis_label = data[1].rstrip('\r\n')
y_axis_label = data[2].rstrip('\r\n')

顺便说一下,matplotlib 1.2 添加了pgf 后端,因此这可能是您想要研究的事情。

相关内容