【问题标题】:Drawing graphs in python - pydotplus error在 python 中绘制图形 - pydotplus 错误
【发布时间】:2018-03-29 10:12:27
【问题描述】:

我迷失在所有用于绘制图形的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 '{'

【问题讨论】:

  • 哪个最好?一个基于意见的问题,如果我见过的话。
  • @ason​​gtoruin:我已经指定了我关心的参数。
  • 你应该阅读help centerHow to Ask
  • 对不起,我对此感到非常沮丧;我已经更改了标题并指定了问题。问题是我不关心我使用哪个库; pydotplus 似乎是最好的选择,但它不起作用。 pydotplus 中出现语法错误。我不知道人们用什么来绘制图表。我想知道什么是已知的。
  • @Reti43:我相信这个例子符合标准。如帖子中所述,我想用彩色节点绘制图表。

标签: python networkx graphviz pydot


【解决方案1】:

问题解决了,感谢@pgv。

  • 问题 1:节点参数需要作为 key=value 对而不是 dict 传递
  • issue 2:fillcolor 本身不起作用,参数样式必须设置为“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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2015-10-03
    • 2011-01-04
    • 2017-03-30
    • 2021-06-05
    相关资源
    最近更新 更多