Search code examples
nodes

amChart 4 Force directed tree dynamic font size


Is this possible to change each nodes font size according node size. For example if one node is larger than one node font size should be bigger, second node is smaller than one node than second node font size should be smaller than one node as on other node font size decrease according their size.

Also it is possible to set max/min font size of nodes min font size 14px of smallest node. max font size 45px of largest node.


Solution

  • You can wait until the nodes load (their "ready" event specifically), after which you can check their measuredWidths, run some math/logic, and determine/assign a fontSize for them (which their labels will automatically inherit), e.g.

    series.nodes.template.events.on('ready', function(event) {
      // Minimum font size 14:
      // Math.max(14, number here);
      // Maximum font size 45:
      // Math.min(45, number here);
      // combined below...
      // half the width of the node, between 14 and 45.
      var fontSize = Math.max(14, Math.min(45, Math.ceil(event.target.measuredWidth * .5)));
      event.target.fontSize = fontSize;
    });
    

    CodePen:

    https://codepen.io/team/amcharts/pen/b440a4d0d82e0bd8587a2799a6e2ddb4

    If you need to check the higher level node as part of your size calculation, that can be accessed via node.dataItem.parent.node (where the first node is a ForceDirectedNodein general, i.e. in event above it would be, event.target.dataItem.parent.node).