Matplotlib和LaTeX Beamer:正确的尺寸。

6

关于matplotlib/Python和latex的集成,有很多问题,但我找不到以下内容:

当我在latex中包含使用savefig()创建的pdf文件时,我总是需要

includegraphics[scale=0.5]{myFile.pdf}

通常情况下,比例尺为0.40.5。考虑到我正在创建A5幻灯片,生成正确大小的PDF文件的正确方法是什么,以便我不需要在LaTeX中指定呢?

请注意,这些不是全尺寸的图像幻灯片,需要适当缩小以允许标题、页脚和说明。


您可以设置图的figsize(以英寸为单位的元组)和dpi。假设将figsize设置为默认值的0.4或0.5,则适合您的beamer幻灯片。 - cphlewis
2个回答

5

参考这篇 matplotlib cookbook,可以创建适用于 Latex 的出版质量图。为了保持所有图形属性(图例等)的恒定大小,应避免在导入图形时进行缩放。建议采用以下方法:

  1. Find the line width of your Latex document in pixels. This can be done, temporarily inserting somewhere in your document, \showthe\columnwidth

  2. Define a helper functions in python that will be used to compute the figure size,

      def get_figsize(columnwidth, wf=0.5, hf=(5.**0.5-1.0)/2.0, ):
          """Parameters:
            - wf [float]:  width fraction in columnwidth units
            - hf [float]:  height fraction in columnwidth units.
                           Set by default to golden ratio.
            - columnwidth [float]: width of the column in latex. Get this from LaTeX 
                                   using \showthe\columnwidth
          Returns:  [fig_width,fig_height]: that should be given to matplotlib
          """
          fig_width_pt = columnwidth*wf 
          inches_per_pt = 1.0/72.27               # Convert pt to inch
          fig_width = fig_width_pt*inches_per_pt  # width in inches
          fig_height = fig_width*hf      # height in inches
          return [fig_width, fig_height]
    
  3. Figures are then produced with,

     import matplotlib
     import matplotlib.pyplot as plt
     # make sure that some matplotlib parameters are identical for all figures
     params = {'backend': 'Agg',
               'axes.labelsize': 10,
               'text.fontsize': 10 } # extend as needed
     matplotlib.rcParams.update(params)
    
     # set figure size as a fraction of the columnwidth
     columnwidth = # value given by Latex
     fig = plt.figure(figsize=get_figsize(columnwidth, wf=1.0, hf=0.3)
     # make the plot
     fig.savefig("myFigure.pdf")
    
  4. Finally this figure is imported in Latex without any scaling,

    \includegraphics{myFigure.pdf}
    

    thus ensuring, among other things, that, say, a 12pt text in matplotlib corresponds to the same font size in the Latex document.


很遗憾,提供的链接不再可用。 只要您提供特定的列宽,wf=1.0hf=0.3是否适用于任何LaTeX文档? - AleB
@AleB,我修复了那个坏链接。很抱歉我不记得这件事,并且已经有一段时间没有使用Latex了,所以我没有答案。 - rth

0

你最好指定你想要的图片的绝对尺寸,而不是比例。(如果更方便的话,你可以指定高度,并使用厘米作为单位)

\includegraphics[height=4in]{myFile.pdf}

更好的做法是定义一个宏来插入您的图像。以下是一个不包含插图(包括标题、填充空间等)的图像插入宏示例。
\newcommand{\plotstandard}[1]{\centerline{\includegraphics[height=4in]{#1}}}

这被称为使用

\plotstandard{myFile.pdf}

可能是关于LaTex最好的在线资源:Wikibook - Beachcomber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接