Wednesday, 06 July 2022

How to calculate keyword frequency and draw the bar chart in PHP

PHP  JpGraph  Text Analysis 

This post shows you how to calculate the keyword frequency from text and draw the bar chart by using the JpGraph library.

Calculate the keyword frequency

Suppose we have a string like this:

$str = "There are two cats on the table. One on the left side is eating an apple, the other on the right side is eating a fish.";

It is easy to calculate the keyword frequency by using the PHP built-in functions.

First, we convert all text to lowercase.

$str = strtolower($str);

Then, we can extract all words from text by using the function str_word_count().

$words = str_word_count($str, 1);

By setting the second parameter's value to be 1, the function str_word_count() returns an array $words with all the words in the string $str. After that, use the function array_count_values() to count all the valules inside the array $words. Actually, it gets the frequency of all the words in the array $words and returns as an array $keywords.

$keywords = array_count_values($words);

If we just want the top 5 keywords, use the function arsort() to sort the array $keywords from highest to lowest and get the first 5 elements by using the function array_splice().

$keywords = array_splice($keywords, 0, 5);

Finally, calculate the percentage of each keyword like this:

$total = count($words);

$frequency = [];
foreach ($keywords as $key => $value) {
    $frequency[$key] = number_format(($value / $total) * 100, 2);

Draw the keyword frequency bar chart

In this example, we use the graph creating library, JpGraph, to draw the keyword frequency bar chart. First, copy the library files under the root path of your website and include the JpGraph files:

require_once ('jpgraph-4.4.1/src/jpgraph.php');
require_once ('jpgraph-4.4.1/src/jpgraph_bar.php');

Then create a graph and set it as autoscaling.

// create a graph 600x400
$graph = new Graph(600, 400);
// use autoscaling 

For the Y grid and axis, we can set like this:

$graph->yaxis->HideTicks(false, false);

For the X axis, we set the labels as the keywords.


We set the graph title as Keyword frequency.

$graph->title->Set("Keyword frequency");

To draw the bar chart, we need to create a BarPlot object with the frequency data. Then add the bar plot to the graph $graph.

// create the bar plot
$barPlot = new BarPlot(array_values($frequency));

// add the bar plot to the graph

Finally, set the bar plot's color and filling color, and display the graph.


// display the graph

The keyword frequency bar chart output is:

Keyword frequency

For this example, the top 5 keywords are the, on, side, is and eating.