【问题标题】:matplotlib - savefig with usetex=Truematplotlib - 使用 usetex=True 的 savefig
【发布时间】:2016-08-08 21:18:23
【问题描述】:

当我启用 usetex=True 时,我在将 matplotlib 创建的图形保存为 .eps 或 .ps 时遇到问题。这在未启用时有效。这是一个例子:

plt.plot([1,2,3], [1,2,3], 'b.')
plt.text(2,2,r'\textbf{(a)} \lambda_{1} value', usetex=True, fontsize=16, fontname='Times New Roman')
plt.savefig('check.eps')

我收到此错误:

File "C:\Python27\lib\site-packages\matplotlib\backends\backend_ps.py", line 671, in draw_tex
thetext = 'psmarker%d' % self.textcnt
AttributeError: 'RendererPS' object has no attribute 'textcnt'

当我启用usetex=True 时,我也无法使用文本命令将字体设置为Time New Roman。

【问题讨论】:

    标签: matplotlib postscript axis-labels tex


    【解决方案1】:

    即使有点晚了,如果其他人搜索这个错误,我想给出一个答案。

    保存eps 文件会启动RendererPS 后端,它会检查plt.rcParams['text.usetex'] 是否设置为True 以初始化其textcnt 属性。由于usetex 仅针对文本对象设置,因此后端不需要处理 LaTeX 并在尝试处理时抛出错误。可悲的是,这种关于 LaTeX 渲染的不一致在 matplotlib 的许多地方都存在。

    如果您无法使用标准 matplotib 功能实现文本格式化,一种解决方案是全局设置 usetexplt.rcParams['text.usetex'] = True。这会使用 LaTeX 渲染图形的所有文本(例如,刻度标签或轴标签)。我建议在任何情况下都这样做,以获得一致的视觉效果。

    关于字体,fontname 参数仅影响标准 matplotlib 格式。对于 LaTeX 渲染,您必须像在 LaTeX 中那样指定字体。要获得像 Times New Roman 这样的字体,您需要加载相应的包,例如mathptmxtimes 包已弃用)plt.rcParams['text.latex.preamble'] = [r'\usepackage{mathptmx}']。当然,该软件包必须安装在本地 LaTeX 安装中。 matplotlib 中的标准字体系列是 sans-serif,因此必须将其更改为带有 plt.rcParams['font.family'] = 'serif' 的 serif。

    最终代码为:

    import matplotlib.pyplot as plt
    
    # LaTeX setup
    plt.rcParams['text.latex.preamble'] = [r'\usepackage{mathptmx}']  # load times roman font
    plt.rcParams['font.family'] = 'serif'  # use serif font as default
    plt.rcParams['text.usetex'] = True  # enable LaTeX rendering globally
    
    plt.plot([1,2,3], [1,2,3], 'b.')
    plt.text(2,2,r'\textbf{(a)} $\lambda_1$ value', fontsize=16)
    plt.savefig('check.eps')
    

    请注意,您必须将数学变量括在美元符号$\lambda_1$ 中,否则您会在 LaTeX 中收到错误或警告。 (另外,单字符下标不需要用大括号括起来)。

    附带说明:在再次关闭usetex 后尝试将图形另存为 eps 时,我遇到了同样的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-25
      • 2014-06-12
      • 2020-06-17
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 2012-10-15
      相关资源
      最近更新 更多