在IPython中使用igraph绘制顶点标签的问题

5

我通常在IPython笔记本上工作,使用以下命令在Windows上打开:

ipython qtconsole --matplotlib inline

我目前使用的是IPython QtConsole 3.0.0,Python 2.7.9和IPython 3.0.0。

我想绘制一个图表,同时还要包括它的标签。

from igraph import *
g = Graph.Lattice([4,4],nei=1,circular=False)
g.vs["label"]=[str(i) for i in xrange(16)]
plot(g, layout="kk")

以这种方式,我获得了图形的内联绘图,但是没有标签,并且对于每个缺失的标签,我会收到以下错误消息。
link glyph0-x hasn't been detected!

其中,x是一个整数。

我还尝试在plot()命令中直接指定标签,使用vertex_label = ...,但没有效果。

我认为标签已经正确定义,问题可能出现在ipython笔记本和/或用于绘制图形的模块中。是否有人可以友善地帮助我解决这个问题?

我也尝试了所有可能的图形格式SVG和PNG,使用下面的命令,但问题仍然存在。

%config InlineBackend.figure_format = 'svg'
%config InlineBackend.figure_format = 'png'
1个回答

3
问题可能存在于Qt及其SVG实现的深处。将图形格式设置为png无济于事,因为igraph仅提供图形对象的SVG表示,因此我怀疑IPython首先创建SVG表示,然后将其栅格化为PNG。目前唯一可以解决该问题的方法是在igraph/drawing/__init__.py中修补Plot类;必须从该类中删除_repr_svg_方法,并添加以下方法:
def _repr_png_(self):
    """Returns a PNG representation of this plot as a string.

    This method is used by IPython to display this plot inline.
    """
    # Create a new image surface and use that to get the PNG representation
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(self.bbox.width),
                                 int(self.bbox.height))
    context = cairo.Context(surface)
    # Plot the graph on this context
    self.redraw(context)
    # No idea why this is needed but Python crashes without this
    context.show_page()
    # Write the PNG representation
    io = BytesIO()
    surface.write_to_png(io)
    # Finish the surface
    surface.finish()
    # Return the PNG representation
    return io.getvalue()

我有点不确定是否应该修改igraph Python接口的官方代码;SVG表示通常更加美观(且具有可伸缩性),但似乎在Windows和Mac OS X上也存在问题。如果任何阅读此帖子的人有更多关于Qt及其SVG实现的经验,我将非常感谢一些帮助来找到此错误的根本原因,以便我们可以保留igraph中绘图的SVG表示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接