0

I am lost in all the python libraries for drawing graphs. I wish I knew one that is flexible and with documentation...

I have spent substantial time playing with networkx to find out that it is not as good for my task (e.g. overlapping labels for bigger graphs).

Now, I am trying to use pydot or pydotplus, but there is no documentation, no reasonable examples out there. Or am I missing something? Pydotplus website provides a reference, but that is not entirely helpful for a beginner.

Now, I am able to draw a graph with pydotplus, but I want to change the node positions (Fruchterman-Reingold algorithm) and especially use colors and sizes with nodes, but I have no idea how.

Sample code:

import pydotplus as ptp

graph = ptp.Dot(graph_type='graph')
edges = [(1,2), (1,3), (2,4), (2,5), (3,5)]
nodes = [(1, "A", "r"), (2, "B", "g"), (3, "C", "g"), (4, "D", "r"), (5, "E", "g")]
for e in edges:
    graph.add_edge(ptp.Edge(e[0], e[1]))
for n in nodes:
    node = ptp.Node(name=n[0], attrs={'label': n[1], 'fillcolor': n[2]} )
    graph.add_node(node)
graph.write_png("file.png")

This throws an exception:

InvocationException: Program terminated with status: 1. stderr follows: 
Error: /tmp/tmpznciMx: syntax error in line 7 near '{'
galapah
  • 379
  • 1
  • 2
  • 14
  • If you want to use pydotplus, you're going to have to get familiar with graphviz. You're generationg a bad dot file, probably because of the way you're attempting to style the nodes. Check the generated file, find some examples of correct usage. – pvg Oct 17 '17 at 16:40
  • FWIW, I don't use any library, I just generate GraphViz DOT files directly. Sure, it's not as convenient as a library, but it means you have full access to everything that GraphViz can do. Of course, that also means that you need to spend a little time learning the DOT language, but the core elements don't take that long to learn. – PM 2Ring Oct 17 '17 at 16:43

1 Answers1

1

Problem solved, thanks to @pgv.

  • issue 1: Node arguments need to be passed as key=value pairs, not a dict
  • issue 2: fillcolor does not work by itself, parameter style must be set to "filled"

corrected code:

import pydotplus as ptp

graph = ptp.Dot(graph_type='graph')
edges = [(1,2), (1,3), (2,4), (2,5), (3,5)]
nodes = [(1, "A", "r"), (2, "B", "g"), (3, "C", "g"), (4, "D", "r"), (5, "E", "g")]
for e in edges:
    graph.add_edge(ptp.Edge(e[0], e[1]))
for n in nodes:
    node = ptp.Node(name=n[0], label= n[1], fillcolor=n[2], style="filled" )
    graph.add_node(node)
graph.write_png("file.png")
galapah
  • 379
  • 1
  • 2
  • 14