Search code examples
pythongraphvizdigraphs

Manipulate existing labels on a digraph object


There's this graphviz digraph object generated from a library.
I'm trying to change the font for the labels...

digraph "something" {
    graph [rankdir=LR]
    node [margin=0 shape=plaintext]
    "something" [label="something" fontsize=30]
    "other-bwd-other" [label=iglo fontsize=30]
    "other-bwd-other-this" [label="this" fontsize=23]
    [...]

Calling

g.attr('graph', fontname='Arial')
g.attr('node', fontname='Arial')

Afterwards has no effect, I guess because those attributes already exist or need to be set before adding nodes?

Is there a way to manipulate certain nodes?
Regex would be fine, but I don't seem to get how to even overwrite a nodes content..
Or maybe rebuild a graph while iterating over the body?


Solution

  • If someone is interested in the super-hacky regex "solution",
    that does the trick, until discovery of the official elegant solution.

    gg = graphviz.Digraph(name=most_common_word.lower(), format='png')
    gg.attr('graph', rankdir='LR')
    gg.attr('node', shape='plaintext', margin='0')
    
    current_dir = os.path.dirname(os.path.realpath(__file__))
    
    for item in generated_graph:
        node_matches = re.findall('\"(.*)\" \[(.*)\]', item.strip())
        edge_matches = re.findall('"(.*)" -> "(.*)"', item.strip())
        if node_matches:
            font_size = re.findall('[0-9]+', node_matches[0][1])
            label = re.findall('label=([a-z]+)', node_matches[0][1])
            if not label:
                label = re.findall('label=\"(.*)\"', node_matches[0][1])
            gg.node(node_matches[0][0], label=label[0], fontsize=font_size[0], fontname=f'{current_dir}/assets/source-sans-pro.ttf')
        if edge_matches:
            gg.edge(edge_matches[0][0], edge_matches[0][1])
    
    gg.render() # gg indeed