简体   繁体   English

如何在 matplotlib 输出中获得与乳胶输出相同的字体(-style、-size 等)?

[英]How to obtain the same font(-style, -size etc.) in matplotlib output as in latex output?

I have one .tex -document in which one graph is made by the python module matplotlib .我有一个.tex文档,其中一张图是由 python 模块matplotlib What I want is, that the graph blends in to the document as good as possible.我想要的是,图表尽可能地融入文档。 So I want the characters used in the graph to look exactly like the other same characters in the rest of the document.所以我希望图表中使用的字符看起来与文档其余部分中的其他相同字符完全相同。

My first try looks like this (the matplotlibrc -file):我的第一次尝试看起来像这样( matplotlibrc文件):

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

For compiling of the .tex in which the PDF output of matplotlib is included, pdflatex is used.为了编译包含matplotlib的 PDF 输出的.tex ,使用了pdflatex

Now, the output looks not bad, but it looks somewhat different, the characters in the graph seem weaker in stroke width.现在,输出看起来不错,但看起来有些不同,图中的字符在笔画宽度上似乎更弱。

What is the best approach for this?最好的方法是什么?

EDIT: Minimum example: LaTeX-Input:编辑:最小示例: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-Script: 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 output: PDF输出:

在此处输入图片说明

The difference in the fonts can be caused by incorrect parameter setting out pictures with matplotlib or wrong its integration into the final document.字体的差异可能是由于使用 matplotlib 设置图片的参数不正确或将其错误集成到最终文档中造成的。 I think problem in text.latex.preamble: \\usepackage{lmodern} .我认为text.latex.preamble: \\usepackage{lmodern} 中的问题 This thing works very badly and even developers do not guarantee its workability, how you can find here .这东西运行起来很糟糕,甚至开发人员也不保证它的可操作性,你怎么能在这里找到 In my case it did not work at all.就我而言,它根本不起作用。

Minimal differences in font associated with font family.与字体系列相关的字体差异最小。 For fix this u need: 'font.family' : 'lmodern' in rc .为了解决这个问题,你需要: 'font.family' : 'lmodern' in rc Other options and more detailed settings can be found here.其他选项和更详细的设置可以在这里找到

To suppress this problem, I used a slightly different method - direct.为了抑制这个问题,我使用了一个稍微不同的方法——直接。 plt.rcParams['text.latex.preamble']=[r"\\usepackage{lmodern}"] . plt.rcParams['text.latex.preamble']=[r"\\usepackage{lmodern}"] It is not strange, but it worked.这并不奇怪,但它奏效了。 Further information can be found at the link above.更多信息可以在上面的链接中找到。


To prevent these effects suggest taking a look at this code:为了防止这些影响,建议看一下这段代码:

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', 
            )

And finally move on to the latex:最后继续讨论乳胶:

\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}

Results结果

pdf文档的缩放

As can be seen from a comparison of two fonts - differences do not exist (1 - MatPlotlib, 2 - pdfLaTeX)从两种字体的比较中可以看出 - 差异不存在(1 - MatPlotlib,2 - pdfLaTeX)字体对比

Alternatively, you can use Matplotlib's PGF backend .或者,您可以使用 Matplotlib 的PGF 后端 It exports your graph using LaTeX package PGF, then it will use the same fonts your document uses, as it is just a collection of LaTeX commands.它使用 LaTeX 包 PGF 导出您的图形,然后它将使用您的文档使用的相同字体,因为它只是 LaTeX 命令的集合。 You add then in the figure environment using input command, instead of includegraphics:然后使用输入命令在图形环境中添加,而不是包含图形:

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

If you need to adjust the sizes, package adjustbox can help.如果您需要调整尺寸,包 adjustbox 可以提供帮助。

I had difficulties getting Eleniums's answer to work for me.我很难让 Eleniums 的答案为我工作。 I specified 'figure.figsize' and 'font.size' in the matplotlib rc-params to be identical to the font size and textwidth of the LaTeX document, but there still was a noticeable difference in the text size of the label.我在 matplotlib rc-params 中指定了'figure.figsize''font.size'与 LaTeX 文档的字体大小和文本textwidth相同,但标签的文本大小仍然存在明显差异。 I finally found out that the label font size in matplotlib is apparently indepentent of 'font.size' .我终于发现 matplotlib 中的标签字体大小显然与'font.size'

The following solution worked perfectly for me:以下解决方案对我来说非常有效:

Python 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')

LaTeX乳胶

\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}

tikzplotlib is here for this exact purpose. tikzplotlib就是为了这个目的。 Instead of savefig() , use而不是savefig() ,使用

import tikzplotlib

tikzplotlib.save("out.tex")

and include the resulting file in your LaTeX document via并将生成的文件包含在您的 LaTeX 文档中

\input{out.tex}

It's also easy to edit in case you need to change things in your plot after you created the file.如果您在创建文件后需要更改绘图中的内容,它也很容易编辑。

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 matplotlib plot 中获得与 latex 相同的字体? - How to get same font in matplotlib plot as latex? 如何避免在matplotlib中调用乳胶(输出到pgf) - How to avoid calling latex in matplotlib (output to pgf) 有没有办法获得与 Jupyter 中相同的 LaTeX 输出,但在 Visual Studio 中? - Is there a way to obtain the same LaTeX output as one gets in Jupyter, but in Visual Studio? 我如何在 BeautifulSoup 中使用其样式定义(如填充、字体大小等)来抓取元素 - How do I web scrape an element using its style definitions like padding, font-size etc. in BeautifulSoup 如何使用 Sphinx 在 LaTeX PDF 输出中更改代码示例字体大小? - How do you change the code example font size in LaTeX PDF output with Sphinx? Python:如何使用“列表文件”的输出来删除/移动/等文件 - Python: How to use output of “listfiles” to delete/ move/ etc. files Tkinter:同一按钮内的文本使用不同的字体(颜色,大小等)吗? - Tkinter: Use different font (color, size, etc.) for the text within the same button? 如何使 pandas.style.to_latex() output header 字段包含在 {} 中? - How to make pandas.style.to_latex() output header fields enclosed in {}? matplotlib乳胶输出中希腊字母以粗体显示 - Greek letters are printed bold in matplotlib latex output matplotlib以像素为单位的规格(大小,颜色等)渲染图像 - matplotlib render image with specs (size, alligment etc.) in pixels
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM