我怎样才能将matplotlib与igraph一起使用?

Ann*_*nan 1 python matplotlib igraph

如何将统计图形(图,轴,图表等)添加到python-igraph中实现的现有图形中?我对matplotlib特别感兴趣,因为我对这个库有经验.

在我的情况下,igraph被用于不同的布局选项.我当前的网络部分约束了x维度,而布局更改了y.我想在图的底部添加一个条形图,列出绑定到网络节点的x坐标的值的频率.

(我没有使用scipy/ipython/pandas库,但还没有)

Tam*_*más 7

这不是一个完整的答案,但是作为评论发布太长了,所以我将其作为答案发布.随意扩展/编辑它.

我已经尝试过组合python-igraphmatplotlib前一段时间(好吧,超过五年前),一般的结论是两者结合是可能的,但是以一种相当复杂的方式.

首先,只有在使用Cairo作为绘图后端时才能使用该组合matplotlib,因为python-igraph使用Cairo作为图形绘制后端(并且它不支持任何其他绘图后端).

接下来,关键的技巧是你可以以某种方式提取Matplotlib图的Cairo表面,然后将这个表面传递给igraph的plot()函数作为绘图目标 - 在这种情况下,igraph不会创建一个单独的图但只是开始绘制给定的表面.然而,在我试验这个时,Matplotlib中没有公共API从图中提取开罗表面,所以我不得不求助于未记录的Matplotlib属性和函数,所以整个事情非常脆弱而且依赖于它严重依赖于我使用的Matplotlib的特定版本 - 但它确实奏效了.

整个过程在邮件列表的这个主题中进行了总结igraph-help.在线程中,我提供了以下Python脚本作为概念验证,为了完整起见,我将其复制到此处:

from matplotlib.artist import Artist
from igraph import BoundingBox, Graph, palettes

class GraphArtist(Artist):
    """Matplotlib artist class that draws igraph graphs.

    Only Cairo-based backends are supported.
    """

    def __init__(self, graph, bbox, palette=None, *args, **kwds):
        """Constructs a graph artist that draws the given graph within
        the given bounding box.

        `graph` must be an instance of `igraph.Graph`.
        `bbox` must either be an instance of `igraph.drawing.BoundingBox`
        or a 4-tuple (`left`, `top`, `width`, `height`). The tuple
        will be passed on to the constructor of `BoundingBox`.
        `palette` is an igraph palette that is used to transform
        numeric color IDs to RGB values. If `None`, a default grayscale
        palette is used from igraph.

        All the remaining positional and keyword arguments are passed
        on intact to `igraph.Graph.__plot__`.
        """
        Artist.__init__(self)

        if not isinstance(graph, Graph):
            raise TypeError("expected igraph.Graph, got %r" % type(graph))

        self.graph = graph
        self.palette = palette or palettes["gray"]
        self.bbox = BoundingBox(bbox)
        self.args = args
        self.kwds = kwds

    def draw(self, renderer):
        from matplotlib.backends.backend_cairo import RendererCairo
        if not isinstance(renderer, RendererCairo):
            raise TypeError("graph plotting is supported only on Cairo backends")
        self.graph.__plot__(renderer.gc.ctx, self.bbox, self.palette, *self.args, **self.kwds)


def test():
    import math

    # Make Matplotlib use a Cairo backend
    import matplotlib
    matplotlib.use("cairo.pdf")
    import matplotlib.pyplot as pyplot

    # Create the figure
    fig = pyplot.figure()

    # Create a basic plot
    axes = fig.add_subplot(111)
    xs = range(200)
    ys = [math.sin(x/10.) for x in xs]
    axes.plot(xs, ys)

    # Draw the graph over the plot
    # Two points to note here:
    # 1) we add the graph to the axes, not to the figure. This is because
    #    the axes are always drawn on top of everything in a matplotlib
    #    figure, and we want the graph to be on top of the axes.
    # 2) we set the z-order of the graph to infinity to ensure that it is
    #    drawn above all the curves drawn by the axes object itself.
    graph = Graph.GRG(100, 0.2)
    graph_artist = GraphArtist(graph, (10, 10, 150, 150), layout="kk")
    graph_artist.set_zorder(float('inf'))
    axes.artists.append(graph_artist)

    # Save the figure
    fig.savefig("test.pdf")

    print "Plot saved to test.pdf"

if __name__ == "__main__":
    test()
Run Code Online (Sandbox Code Playgroud)

一句警告:我没有测试上面的代码,我现在无法测试,因为我现在没有在我的机器上使用Matplotlib.它曾经在五年前使用当时的Matplotlib版本(0.99.3)工作.如果没有重大修改,它现在可能无法正常工作,但它显示了一般的想法,希望它不会太复杂,无法适应.

如果您已设法让它适合您,请随时编辑我的帖子.