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

时间:2016-03-21 15:42:50

标签: python matplotlib igraph

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

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

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

1 个答案:

答案 0 :(得分:6)

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

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

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

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

整个过程在igraph-help邮件列表的this thread中进行了总结。在线程中,我提供了以下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()

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

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