Obtain the total (count) of the contents associated with a nested taxonomy (only in the parent taxonomy)
I tried something similar I think, here's my code but keep in mind it's not perfect.

first get alle the terms

$node_storage = \Drupal::entityTypeManager()-&gt;getStorage('node');
$nodes = $node_storage-&gt;loadMultiple();
$node_tags = [];
foreach ($nodes as $node) {
  if ($node-&gt;hasField('field_terms')) {
    foreach ($node-&gt;get('field_terms')-&gt;getValue() as $value) {
      array_push($node_tags, $value);
    }
  }
}


after that you count all the terms

foreach ($node_tags as $key) {
  if (isset($count[$key['target_id']])) {
    $count[$key['target_id']]++;
  }
  else {
    $count[$key['target_id']] = 1;
  }
}
arsort($count);


then (and this still needs a lot of work) you search for them

$tags = $terms_storage-&gt;loadTree('tid');
$i=0;
foreach ($count as $key =&gt; $c) {
  foreach ($tags as $tag){
    if($tag-&gt;tid == $key){
     //here you can get the $tag-&gt;tid
     //you can get $tag-&gt;name
     //time used = $c
    }
  }
  $i++;
}


if you want to get the other terms

foreach ($tags as $tag){
  if(!array_key_exists($tag-&gt;tid,$count)){
   //here you get the same info
  }
}