Building a Tag Cloud (logic)

Once we have the data we want, we can build the logic to make the cloud.
Here the logic is extremely simple (no wonder I’ve made a tutorial about it).

The idea is to assign a minimum font-size in “pt” to the least occured tag. In our case we have taken 8pt. Since this 8pt size is applicable to the XML tag (our example), whose tag count is 3. We need to find a multiplying factor for all the tags, that will give us their respective font sizes.

The multiplying factor should take into account, the tags count, and the total of the tag count, which in turn is the percentage of occurance for that tag. So if the factor is x, tag count is 3, tag count sum is 58 and font size is 8, the equation would be

(3 / 58) * x = 8
which gives us x as 
x = (58 / 3) * 8

Now this x has to be multiplied to the % factor of that tag,
to get it's font size value

tag[http] = (10 / 58) * ( (58 / 3) * 8 )

so lets go with PHP,

$min_val = min($tags);
$font_multiplier = ($tag_sum / $min_val) * 8;

// assign the the font sizes
foreach($tags as $key => $value) {
  $tags[$key] = ($value / $tag_sum) * $font_multiplier;
}

Now is the time to display the tags, and link it to what ever, The spacing for each tag word would be fixed I’ll keep it 15pt. Its upto your design to change it!

foreach($tags as $key=>$value) {
  echo "<span style='font-size: {$value}pt; font-family: 
        tahoma;'>$key</span><span style='font-size: 15pt; font-family: 
        tahoma;'>  </span>";
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.