将igraph图保存为eps格式

3 投票
2 回答
2629 浏览
提问于 2025-04-18 14:12

在igraph中将图形保存为eps格式。

我需要把igraph中的图形保存为图片,但要用eps格式。

我有这个:

def _plot(g, membership=None):
    visual_style = {}
    visual_style["vertex_size"] = 24
    visual_style["layout"] = g.layout("kk")
    visual_style["bbox"] = (400, 300)
    visual_style["margin"] = 20
    for vertex in g.vs():
        vertex["label"] = vertex.index + 1
    if membership is not None:
        for vertex in g.vs():
            if(membership[vertex.index] == 0):
                vertex["color"] = "gray"
            else:
                vertex["color"] = "white"
            if(membership[vertex.index] == 0):
                vertex["shape"] = "circle"
            else:
                vertex["shape"] = "rectangle"
        visual_style["vertex_color"] = g.vs["color"]
        visual_style["vertex_shape"] = g.vs["shape"]
    visual_style["vertex_label_color"] = "black"
    visual_style["vertex_label_dist"] = -0.4
    igraph.plot(g, **visual_style)

if __name__ == "__main__":
    g = igraph.Nexus.get("karate")
    cl = g.community_fastgreedy()
    membership = cl.as_clustering(2).membership
    _plot(g, membership)

我尝试了这个:

(1)
igraph.plot(g,'graph.eps',**visual_style)

(2)
import matplotlib.pyplot as plt
igraph.plot(g,'graph.eps',**visual_style)
plt.savefig('graph.eps', format='eps', dpi=1000)

但是(1)和(2)都不行,有人能帮我吗?

2 个回答

1

EPS和PS其实差不多,简单来说,EPS(封装的PostScript)文件就是PS文件,只是多了一些限制。其中一个限制是,EPS文件必须包含一个叫做BoundingBox的DSC注释,这个注释用来说明图形的“边界”。你通常可以用一个合适的转换工具把PS文件转换成EPS文件,这个工具会“推测”出边界并把这个额外的注释加到文件里。所以,我的建议是先把图形输出为PS格式,然后再用ps2eps工具把它转换成EPS格式。还有一种方法是先生成一个SVG格式的图形,然后用一个支持SVG的工具(比如Inkscape)把它转换成EPS格式。Inkscape甚至提供了命令行参数,可以让你在批处理脚本中完成这个转换。

2

很遗憾,igraphplot功能只支持生成PDF、PNG、SVG和PS格式的文件。这就是为什么你第一种方法不成功的原因。

至于你第二种方法,igraph的图形无法直接绘制到matplotlib的绘图区域。不过,你可以把igraph的图形绘制到matplotlib创建的Cairo SVG画布上(这时需要把渲染上下文作为参数传给plot)。

这个方法的详细说明可以在这里找到:https://lists.nongnu.org/archive/html/igraph-help/2010-06/msg00098.html

所以,虽然有点复杂,但这是可行的。另一个问题是,如果你能避免使用EPS格式,通常现代工具是可以做到的。

撰写回答