I have a tree represented by this string (this is a decision tree made by scratch): {'index': 1, 'right': {'index': 0, 'right': 'no', 'value': 'overcast', 'left': 'Yes'}, 'value': 'Mild', 'left': {'index': 0, 'right': {'index': 0, 'right': 'Yes', 'value': 'overcast', 'left': 'Yes'}, 'value': 'rain', 'left': {'index': 0, 'right': 'Yes', 'value': 'rain', 'left': 'Yes'}}}
and I'd like to represent it (with edges and nodes using Graphviz). To print it I use this function in Python:
def print_tree(node, depth=0):
filename = outlook.csv'
dataset = load_csv(filename)
columns = dataset[0]
if isinstance(node, dict):
print('%s[%s = %s]' % ((depth * ' ', (columns[node['index']]), node['value'])))
print_tree(node['left'], depth+1)
print_tree(node['right'], depth+1)
else:
print('%s[%s]' % ((depth*' ', node)))
I'd like to use Digraph from GraphViz from graphviz import Digraph
def createGraph(node):
dot = Digraph(comment="experiment")
def graph(node):
if isinstance(node, dict):
dot.node(str(id(node)))
dot.edge(str(id(node)) , str(id(node['right'])))
graph(node['left'])
graph(node['right'])
else:
dot.node(str(id(node)), str(node))
dot.render('test-output/roundround5.gv', view=True)
'test-output/round.gv.pdf'
graph(node)
but obviously code is wrong. Can anybody help?
There's some syntax errors in your code blocks, the filename outlook.csv
is not quoted correctly, and there's an extra string 'test-output/round.gv.pdf'
on the end of the graphing block.
The main problem though seems to be that you are building a new Digraph
object for every call to graph()
, and you are calling graph recursively. Instead you need to make one Digraph
, and pass that into the first call to graph
, and then recursively add the graph nodes.
Can you expand your question a bit - address the syntax errors and then provide an example of an errors or incorrect output you are seeing?