如何在 matplotlib 中“缩小”绘图,保持所有尺寸比例相同,但以英寸为单位减小尺寸?

新手上路,请多包涵

我正在使用 matplotlib 绘图,我遇到的一个问题是标准绘图尺寸似乎有可笑的巨大尺寸(以英寸为单位)。 MPL 的默认 dpi 值似乎设置为 100dpi ,但生成的图尺寸为 6 英寸以上。问题是,如果我将其另存为 pdf,则直接大小太大而无法放在科学论文中(我宁愿将其设置为“列大小”,就像一英寸或两英寸宽)。

但是,如果您直接指定 figsize 就像

fig, ax = plt.subplots(figsize=[2.,3.])

字体大小和标记大小保持相同的英寸大小,导致相对较大的图形项目和丑陋的图形。我更喜欢默认情况下出现的相同比例,但缩小到不同的英寸尺寸。

我知道有两种解决方法。要么将图形保存为标准尺寸(大约为 8 x 6 英寸或其他尺寸),然后在将其插入 LaTeX 时对其进行缩放。或者手动遍历所有图形元素,并更改字体大小、标记大小和图形大小以使其完美。

在某些情况下你不能做前者,而后者又极其乏味。我必须为每个图形元素找出合适的尺寸,以保持其与默认比例相同。

那么,是否还有另一个快速选项可以更改图形大小,同时还可以缩放默认情况下的所有内容?

原文由 Marses 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

通常,为整个脚本设置不同的字体大小就足够了。

 import matplotlib.pyplot as plt
plt.rcParams["font.size"] =7

完整示例:

 import matplotlib.pyplot as plt
plt.rcParams["font.size"] =7

fig, ax = plt.subplots(figsize=[2.,3.], dpi=100)
ax.plot([2,4,1], label="label")
ax.set_xlabel("xlabel")
ax.set_title("title")
ax.text( 0.5,1.4,"text",)
ax.legend()

plt.tight_layout()
plt.savefig("figure.pdf", dpi="figure")
plt.savefig("figure.png", dpi="figure")
plt.show()

在此处输入图像描述在此处输入图像描述

原文由 ImportanceOfBeingErnest 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可能想询问期刊是否使用 width=\columnwidth ,例如,

 \includegraphics[width=\columnwidth]{example-image}

是可以接受的。虽然这是重新缩放,但它会适应当前的列宽,因此这可能对期刊足够友好。

如果没有,也许可以向他们(或在该期刊上发表过文章的其他作者)索取典型论文用来包含图形的 LaTeX 样本,或有关如何生成图形的建议。

也可能是期刊根本不想 放大 光栅图像,因为这会使图像看起来模糊。缩小光栅图像可能不是问题,而缩放非光栅图像可能根本不是问题。


如果一切都失败了,你可以使用 LaTeX 本身来重新缩放由 matplotlib 生成的 pdf。下面, make_plot 函数(取自 matplotlib 示例库)生成 /tmp/tex_demo.pdfrescale_pdf 函数重新缩放 tex_demo.pdf 并将结果写入 /tmp/tex_demo-scaled.pdfrescale_pdf 函数调用 pdflatex 通过 subprocess 模块。

调整LaTeX模板中的 paperheightpaperwidth 参数

paperheight=2.25in,
paperwidth=3in,

控制重新缩放的 pdf 图的大小。


 import subprocess
import os
import textwrap
import numpy as np
import matplotlib.pyplot as plt

def make_plot(filename):
    """https://matplotlib.org/users/usetex.html"""
    # Example data
    t = np.arange(0.0, 1.0 + 0.01, 0.01)
    s = np.cos(4 * np.pi * t) + 2

    # fig, ax = plt.subplots(figsize=(2, 3))

    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    fig, ax = plt.subplots()
    ax.plot(t, s)

    ax.set_xlabel(r'\textbf{time} (s)')
    ax.set_ylabel(r'\textit{voltage} (mV)',fontsize=16)
    ax.set_title(r"\TeX\ is Number "
              r"$\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!",
              fontsize=16, color='gray')
    # Make room for the ridiculously large title.
    plt.subplots_adjust(top=0.8)

    plt.savefig(filename)

def rescale_pdf(filename):
    stub, ext = os.path.splitext(filename)
    print('begin rescale')
    template = textwrap.dedent(r'''
        \documentclass{article}

        %% https://tex.stackexchange.com/a/46178/3919
        \usepackage[
                paperheight=2.25in,
                paperwidth=3in,
                bindingoffset=0in,
                left=0in,
                right=0in,
                top=0in,
                bottom=0in,
                footskip=0in]{geometry}
        \usepackage{graphicx}

        \begin{document}
        \pagenumbering{gobble}
        \begin{figure}
        %% https://tex.stackexchange.com/questions/63221/how-to-deal-with-pdf-figures
        \includegraphics[width=\linewidth]{%s}
        \end{figure}

        \end{document}''' % (stub,))

    tex_filename = 'result.tex'
    with open(tex_filename, 'w') as f:
        f.write(template)

    proc = subprocess.Popen(['pdflatex', '-interaction', 'batchmode', tex_filename])
    output, err = proc.communicate()

filename = '/tmp/tex_demo.pdf'
dirname = os.path.dirname(filename)
if dirname:
    os.chdir(dirname)
make_plot(filename)
rescale_pdf(filename)

原文由 unutbu 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题