在 Python 的 igraph 中,你能为一个图表添加图例和标题吗?就我所见,手册和教程中都没有提到。不过在 R 中是可以实现的。
plot
函数在后台创建了一个Plot
对象,将正在绘制的图形添加到绘图本身中,为其创建适当的Cairo表面,然后开始在Cairo表面上绘制图形。如果您只使用图形作为参数简单地调用plot
,所有这些都会在幕后发生。但是,您可以手动创建一个Plot
对象,然后在绘制它之前向其中添加标签,例如:>>> plot = Plot("plot.png", bbox=(600, 600), background="white")
plot
的变量,它是igraph.drawing.Plot
的实例。该图由一个Cairo图像表面支持,宽度为600像素,高度为600像素,并最终保存到名为plot.png
的文件中(也可以直接在Plot
构造函数的第一个参数中提供Cairo表面)。调用plot.redraw()
会绘制图形,但不会立即保存。调用plot.save()
会绘制图形(如果尚未绘制),然后将其保存到指定的文件名中。Add an arbitrary object to the plot that has a __draw__
method. Graph
objects have such a method so you can add a graph to the plot as follows:
>>> g = Graph.GRG(100, 0.2)
>>> plot.add(g, bbox=(20, 20, 580, 580))
Grab its surface
property to access the Cairo surface on which the drawing is done, construct a Cairo drawing context with this surface, and then draw on the plot directly with Cairo using the drawing context.
igraph.drawing.text
包中提供了一个名为TextDrawer
的类,可以帮助我们解决换行和对齐问题。我们只需要创建一个TextDrawer
,然后调用它的draw_at
方法,在给定位置添加标签即可:>>> import cairo
>>> context = cairo.Context(plot.surface)
>>> text_drawer = TextDrawer(context, text="Test label", halign=TextDrawer.LEFT)
>>> text_drawer.draw_at(x=100, y=100)
from igraph import Graph, Plot
from igraph.drawing.text import TextDrawer
import cairo
# Construct the plot
plot = Plot("plot.png", bbox=(600, 650), background="white")
# Create the graph and add it to the plot
g = Graph.GRG(100, 0.2)
plot.add(g, bbox=(20, 70, 580, 630))
# Make the plot draw itself on the Cairo surface
plot.redraw()
# Grab the surface, construct a drawing context and a TextDrawer
ctx = cairo.Context(plot.surface)
ctx.set_font_size(36)
drawer = TextDrawer(ctx, "Test title", halign=TextDrawer.CENTER)
drawer.draw_at(0, 40, width=600)
# Save the plot
plot.save()
TextDrawer
的draw
或draw_at
方法来构造(当然,在每次调用之间需要调整TextDrawer
的text
属性)。您可以使用标准的Cairo调用在图例周围绘制框。您还可以使用igraph.drawing.shapes
中的节点绘制类来绘制节点形状,类似于igraph在绘制图形时使用的形状。
plot
来添加绘图标题的可能性,但我认为除非有人发送补丁,否则不会实现绘图图例。 - Tamás