在 python 中绘制图表 - pydotplus 错误

Drawing graphs in python - pydotplus error

我迷失在所有用于绘制图形的python 库 中。我希望我知道一个灵活且有文档的...

我花了很多时间玩 networkx,发现它不太适合我的任务(例如,重叠标签用于更大的图形)。

现在,我正在尝试使用 pydotpydotplus,但是没有文档,也没有合理的示例。或者我错过了什么? Pydotplus 网站提供了参考,但对初学者帮助不大。

现在,我可以使用 pydotplus 绘制图形,但我想更改节点位置(Fruchterman-Reingold 算法),尤其是 使用颜色和大小与节点,但我不知道如何。

示例代码:

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")

这会引发异常:

InvocationException: Program terminated with status: 1. stderr follows: 
Error: /tmp/tmpznciMx: syntax error in line 7 near '{'

问题已解决,感谢@pgv。

  • 问题 1:节点参数需要作为键=值对传递,而不是字典
  • 问题2:fillcolor自己不行,参数style必须设置为"filled"

更正代码:

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")