I am trying to build a tree structure using Python’s anytree library. However, I am facing an issue with sharing a node (specifically node 984) among multiple parents. Here is my code:
from anytree import Node, RenderTree
from anytree.exporter import UniqueDotExporter
import numpy as np
# Sample data
data = np.array([
[1000., 1001., 998., 988., 980., 1003.],
[1000., 997., 1000., 979., 1002., 1000.],
[1000., 1003., 996., 1006., 1003., 1002.],
[1000., 988., 999., 984., 972., 970.],
[1000., 1000., 1032., 984., 982., 976.],
[1000., 1000., 1002., 971., 966., 963.]
])
# Recursive function to build the tree structure
def add_to_tree(tree, path):
node = tree
for value in path:
if value not in node:
node[value] = {'count': 0, 'children': {}}
node[value]['count'] += 1
node = node[value]['children']
# Initialize the tree
tree = {}
# Build the tree
for row in data:
add_to_tree(tree, row)
# Given tree structure dictionary
tree_structure = tree
# Function to create hierarchical tree nodes
def create_tree(tree_dict, parent=None):
for key, value in tree_dict.items():
node = Node(str(key), parent=parent)
create_tree(value['children'], parent=node)
# Create the tree
root = Node("1000.0")
create_tree(tree_structure[1000.0]['children'], parent=root)
# Generate the tree diagram
output_path = "full_tree.png"
UniqueDotExporter(root).to_picture(output_path)
print(f"Tree diagram saved to {output_path}")
# Display the generated tree diagram in Colab
from IPython.display import Image
Image(output_path)
enter image description here
But I want this type
enter image description here
I tried Chatgpt, not working.
New contributor
user25379401 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.