简体   繁体   English

将 matplotlib 图形另存为 .pdf_tex

[英]Save matplotlib figures as .pdf_tex

In Inkscape, there is the possibility of saving pdf files along with generating pdf_tex files for automatic formatting into a Latex file.在 Inkscape 中,可以保存 pdf 文件以及生成 pdf_tex 文件以自动格式化为 Latex 文件。 This can be specified by checking a box after clicking on save and specifying the extension as .pdf .这可以通过在单击保存并将扩展名指定为.pdf后选中一个框来指定。

I'm interested in directly saving, from my python script, matplotlib figures in that specific format.我有兴趣直接从我的 python 脚本中以特定格式保存 matplotlib 图形。

Does this possibility exist or can it be done with some tricks?这种可能性是否存在或者可以通过一些技巧来完成?

An option is to export a pdf from matplotlib and then use inkscape programmatically, ie through the command line interface to let it create the desired format.一种选择是从 matplotlib 导出 pdf,然后以编程方式使用 inkscape,即通过命令行界面让它创建所需的格式。

import matplotlib.pyplot as plt

plt.bar(x=[1,2], height=[3,4], label="Bar")
plt.legend()
plt.xlabel("Label")
plt.title("title")

def savepdf_tex(fig, name, **kwargs):
    import subprocess, os
    fig.savefig("temp.pdf", format="pdf", **kwargs)
    incmd = ["inkscape", "temp.pdf", "--export-pdf={}.pdf".format(name),
             "--export-latex"] #"--export-ignore-filters",
    subprocess.check_output(incmd)
    os.remove("temp.pdf")


savepdf_tex(plt.gcf(), "latest")

plt.show()

Also note that matplotlib can save in the pgf format.另请注意,matplotlib 可以保存为pgf格式。 It's definitely worth trying as an alternative to the above.作为上述方法的替代品,绝对值得尝试。 See this example , and append plt.savefig("filename.pgf") to it.请参阅此示例,并将plt.savefig("filename.pgf")附加到它。 In the latex code use \input{filename.pgf} .在乳胶代码中使用\input{filename.pgf}

As matplotlib backend作为 matplotlib 后端

I created a matplotlib backend a few years ago specifically to support this feature.几年前我专门创建了一个matplotlib 后端来支持这个功能。 However, it is only compatible with older matplotlib versions and must be updated (I would appreciate any contributions).但是,它仅与较旧的 matplotlib 版本兼容,并且必须进行更新(我将不胜感激)。

Directly from your script直接来自您的脚本

@ImportanceOfBeingErnest has already mentioned this. @ImportanceOfBeingErnest已经提到了这一点。 However, if that solution fails, try it with --export-filename or -o instead of --export-pdf .但是,如果该解决方案失败,请尝试使用--export-filename-o而不是--export-pdf

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM