Search code examples
pythonnetworkxgraphvizdotpygraphviz

Passing extra arguments to networkx graphviz_layout not working


I want to pass an extra argument to the graphviz_layout(), which I am doing, but it's not doing anything. I have also tried passing other arguments, but same problem.

It is correctly recognizing it, because if I change the argument I pass to something nonsensical I get an error.

I am referring to this documentation: https://graphviz.org/doc/info/attrs.html#d:rankdir

from networkx.drawing.nx_agraph import graphviz_layout

G = model.block_tree.tree
pos = graphviz_layout(G, prog='dot', root=0, args='-Grankdir="LR"')

plt.title(r"Blockchain with Selfish Mining ($\alpha$ = {})".format(alpha))
nx.draw_networkx_nodes(G, pos, node_color=color_vector, node_shape='s', node_size=300)
nx.draw_networkx_edges(G, pos, edgelist=G.edges(), arrows=True)
nx.draw_networkx_labels(G, pos, font_size=10, font_color="white")
plt.show()

Does anyone have an idea why it's not working?

This is the graph that I am producing. I would expect it to rotate, so that it is horizontal, but it's not...

enter image description here

Does anyone have an idea why? I'd be super grateful. Thanks in advance!

PS: There are some related posts, but none worked for me...


Solution

  • There's a conflict between the rankdir argument you're providing and the 'root' argument. If you remove the latter, it should respect your ordering.

    Because I don't have your data, I made a simple example:

    import matplotlib.pyplot as plt
    from networkx.drawing.nx_agraph import graphviz_layout
    import networkx as nx
    
    G = nx.Graph()
    
    G.add_nodes_from([0, 1])
    G.add_edge(0, 1)
    pos = graphviz_layout(G, prog='dot', root=0, args='-Grankdir="LR"')
    
    nx.draw_networkx_nodes(G, pos, node_shape='s', node_size=300)
    nx.draw_networkx_edges(G, pos, edgelist=G.edges(), arrows=True)
    nx.draw_networkx_labels(G, pos, font_size=10, font_color="white")
    plt.show()
    
    

    This produces the following output: enter image description here

    But if I just remove the root=0 argument, I get:

    enter image description here