【问题标题】:How to obtain the same font(-style, -size etc.) in matplotlib output as in latex output?如何在 matplotlib 输出中获得与 Latex 输出中相同的字体(-style、-size 等)?
【发布时间】:2013-07-16 21:20:39
【问题描述】:

我有一个.tex-document,其中一个图表是由python 模块matplotlib 制作的。我想要的是,图表尽可能好地融入文档。所以我希望图表中使用的字符看起来与文档其余部分中的其他相同字符完全相同。

我的第一次尝试看起来像这样(matplotlibrc-file):

text.usetex   : True
text.latex.preamble: \usepackage{lmodern} #Used in .tex-document
font.size    : 11.0 #Same as in .tex-document
backend: PDF

对于包含matplotlib 的PDF 输出的.tex 的编译,使用pdflatex

现在,输出看起来还不错,但看起来有些不同,图中字符的笔画宽度似乎较弱。

最好的方法是什么?

编辑:最小示例:LaTeX 输入:

\documentclass[11pt]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}

\begin{document}

\begin{figure}
\includegraphics{./graph}
\caption{Excitation-Energy}
\label{fig:graph}
\end{figure}

\end{document}

Python 脚本:

import matplotlib.pyplot as plt
import numpy as np

plt.plot([1,2,3,4])
plt.xlabel("Excitation-Energy")
plt.ylabel("Intensität")
plt.savefig("graph.pdf")

PDF 输出:

【问题讨论】:

  • 图片的缩放比例是 100% 吗?你在使用 \includefigure[width=??] 吗?这可能是问题
  • 您能否添加一个指向输出示例的链接,以及用于生成它的 python 代码和乳胶?如果没有更多信息,这将很难调试。
  • 一个很好的起点是这个文档wiki.scipy.org/Cookbook/Matplotlib/LaTeX_Examples
  • 看看the psfrag package。它允许您替换 PostScript 图形中的标签。这样,您的绘图标签不仅看起来与文档的文本完全相同,而且将 与文本的其余部分一样。
  • 作为me previous comment 的更新,显然是matplotlib 和psfrag are no longer friends

标签: python matplotlib tex


【解决方案1】:

字体的差异可能是由于使用 matplotlib 设置图片的参数不正确或错误地将其集成到最终文档中造成的。 我认为 text.latex.preamble: \usepackage{lmodern} 中的问题。这东西效果很差,甚至开发人员也不保证它的可操作性,how you can find here。就我而言,它根本不起作用。

与字体系列相关的字体差异很小。为了解决这个问题,你需要:'font.family' : 'lmodern' in rc。 其他选项和更详细的设置可以找到here.

为了抑制这个问题,我使用了一种稍微不同的方法——直接。 plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]。 这并不奇怪,但它奏效了。更多信息可以在上面的链接中找到。


为防止这些影响,建议查看以下代码:

import matplotlib.pyplot as plt

#Direct input 
plt.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]
#Options
params = {'text.usetex' : True,
          'font.size' : 11,
          'font.family' : 'lmodern',
          'text.latex.unicode': True,
          }
plt.rcParams.update(params) 

fig = plt.figure()

#You must select the correct size of the plot in advance
fig.set_size_inches(3.54,3.54) 

plt.plot([1,2,3,4])
plt.xlabel("Excitation-Energy")
plt.ylabel("Intensität")
plt.savefig("graph.pdf", 
            #This is simple recomendation for publication plots
            dpi=1000, 
            # Plot will be occupy a maximum of available space
            bbox_inches='tight', 
            )

最后继续讲乳胶:

\documentclass[11pt]{scrartcl}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{graphicx}

\begin{document}

\begin{figure}
    \begin{center}
        \includegraphics{./graph}
        \caption{Excitation-Energy}
        \label{fig:graph}
    \end{center}
\end{figure}

\end{document}

结果

从两种字体的比较中可以看出 - 不存在差异 (1 - MatPlotlib,2 - pdfLaTeX)

【讨论】:

    【解决方案2】:

    或者,您可以使用 Matplotlib 的 PGF backend。它使用 LaTeX 包 PGF 导出您的图形,然后它将使用您的文档使用的相同字体,因为它只是 LaTeX 命令的集合。然后使用输入命令而不是 includegraphics 在图形环境中添加:

    \begin{figure}
      \centering
      \input{your_figure.pgf}
      \caption{Your caption}
    \end{figure}
    

    如果您需要调整尺寸,package adjustbox 可以提供帮助。

    【讨论】:

      【解决方案3】:

      tikzplotlib 正是为了这个目的。而不是savefig(),使用

      import tikzplotlib
      
      tikzplotlib.save("out.tex")
      

      并通过

      将生成的文件包含在您的 LaTeX 文档中
      \input{out.tex}
      

      它也很容易编辑,以防您在创建文件后需要更改绘图中的内容。

      【讨论】:

        【解决方案4】:

        我很难让 Eleniums 的答案为我工作。我在 matplotlib rc-params 中指定'figure.figsize''font.size' 与LaTeX 文档的字体大小和textwidth 相同,但是标签的文本大小仍然存在明显差异。我终于发现matplotlib中的标签字体大小显然与'font.size'无关。

        以下解决方案非常适合我:

        Python

        W = 5.8    # Figure width in inches, approximately A4-width - 2*1.25in margin
        plt.rcParams.update({
            'figure.figsize': (W, W/(4/3)),     # 4:3 aspect ratio
            'font.size' : 11,                   # Set font size to 11pt
            'axes.labelsize': 11,               # -> axis labels
            'legend.fontsize': 11,              # -> legends
            'font.family': 'lmodern',
            'text.usetex': True,
            'text.latex.preamble': (            # LaTeX preamble
                r'\usepackage{lmodern}'
                # ... more packages if needed
            )
        })
        
        # Make plot
        fig, ax = plt.subplots(constrained_layout=True)
        ax.plot([1, 2], [1, 2])
        ax.set_xlabel('Test Label')
        fig.savefig('test.pdf')
        

        乳胶

        \documentclass[11pt]{article}    % Same font size
        \usepackage[paper=a4paper, top=25mm, 
                    bottom=25mm, textwidth=5.8in]{geometry}    % textwidth == W
        \usepackage{lmodern}
        
        % ...
        
        \begin{figure}[ht]
            \centering
            \includegraphics{test.pdf}
            \caption{Test Title}
        \end{figure}
        

        【讨论】:

          猜你喜欢
          • 2016-06-19
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 2014-12-28
          • 2021-08-01
          • 2019-07-02
          • 2021-02-03
          • 1970-01-01
          相关资源
          最近更新 更多