JSFiddle - React, Tailwind, and code Playground

by saurabhkolhe

HTML

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/sankey.js"></script>
<script src="https://code.highcharts.com/modules/organization.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/accessibility.js"></script>

<figure class="highcharts-figure">
    <div id="container"></div>
</figure>

JavaScript

// Define your tree data
const treeData = {
  name: 'Root',
  children: [
    {
      name: 'Child 1',
      children: [
        { name: 'Leaf 1' },
        { name: 'Leaf 2' }
      ]
    },
    {
      name: 'Child 2',
      children: [
        { name: 'Leaf 3' },
        { name: 'Leaf 4' }
      ]
    }
  ]
};

// Function to flatten the tree data
function flattenData(node, x, y) {
  const data = [{ name: node.name, x, y }];
  if (node.children) {
    const numChildren = node.children.length;
    let offsetY = y - (numChildren - 1) * 20 / 2;
    node.children.forEach((child) => {
      const childData = flattenData(child, x + 100, offsetY);
      data.push(...childData);
      offsetY += 20;
    });
  }
  return data;
}

// Flatten the tree data
const flatData = flattenData(treeData, 0, 0);

// Create an array to store connecting lines
const connectingLines = [];

// Function to add connecting lines between parent and child nodes
function addConnectingLines(node) {
  if (node.children) {
    node.children.forEach(child => {
      connectingLines.push({
        type: 'path',
        linkedTo: child.name, // Match with child node by name
        lineWidth: 2,
        color: 'gray'
      });
      addConnectingLines(child);
    });
  }
}

// Add connecting lines
addConnectingLines(treeData);

// Create the Highcharts chart
Highcharts.chart('container', {
  chart: {
    type: 'scatter',
    height: 400,
    inverted: true
  },
  title: {
    text: 'Custom Tree Chart'
  },
  plotOptions: {
    scatter: {
      marker: {
        radius: 8
      },
      tooltip: {
        pointFormatter: function () {
          return this.name;
        }
      }
    }
  },
  series: [{
    data: flatData
  }],
  xAxis: {
    visible: false // Hide the X axis
  },
  yAxis: {
    visible: false // Hide the Y axis
  },
  // Add the connecting lines as plot lines
  plotLines: connectingLines
});