draw vertex labels with a background

Looking through the documentation and the source, I think I can tell that there is no straightforward way of drawing vertex labels with a background. This would occasionally be helpful to make labels more readable, so it would be a nice feature to have.

What would it take to add this functionality? Would it be enough to subclass TextDrawer and get draw to draw a rectangle before drawing the text?

Are there any code examples that I could draw inspiration from?

1 Like

Yes, it should be enough to subclass TextDrawer if you are using the Cairo backend. It seems a bit messy, though; there are two entry points of TextDrawer that are used by DefaultGraphDrawer, depending on whether the vertex_label_dist property is set. If vertex_label_dist is not given, the label will be drawn in the center of the vertex and then you have self.bbox within the draw() function that you can use to obtain the boundaries of the vertex. However, if vertex_label_dist is given, the draw_at() method is used, and you only have the anchor point of the text to work from. In both cases, you’ll need to call the text_extents() method of TextDrawer to obtain the width and height of the text itself.

You’ll also need to construct your own DefaultGraphDrawer instance to be able to override the TextDrawer that the graph drawer uses; something like:

class FilledTextDrawer(TextDrawer):
    def draw(self, ...):
        ...override stuff here...

    def draw_at(self, ...):
        ...override stuff here...


def plot_graph(graph, context, bbox, *args, **kwds):
    drawer = DefaultGraphDrawer(context, bbox, label_drawer_factory=FilledTextDrawer)
    drawer.draw(graph, *args, **kwds)

my_graph = Graph.GRG(100, 0.2)
my_graph.__plot__ = plot_graph
plot(my_graph)

This is completely untested, but I think it should work, or at least should be enough to point you in the right direction.

1 Like