首页 > 解决方案 > 将 matplotlib 图形另存为 .pdf_tex

问题描述

在 Inkscape 中,可以保存 pdf 文件以及生成 pdf_tex 文件以自动格式化为 Latex 文件。这可以在单击将扩展名指定为 .pdf 的保存后选中一个框来指定。

我有兴趣直接从我的 python 脚本中以特定格式保存 matplotlib 图形。

这种可能性是否存在或者可以通过一些技巧来完成?

谢谢

标签: pythonmatplotliblatexinkscape

解决方案


一种选择是从 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()

另请注意,matplotlib 可以保存pgf格式。作为上述方法的替代品,绝对值得尝试。请参阅此示例,并附plt.savefig("filename.pgf")加到它。在乳胶代码中使用\input{filename.pgf}.


推荐阅读