# CakePHP 4 Visualized Data Using ChartJS

> This tutorial will show how to count and visualized data using ChartJS in CakePHP 4

- URL: https://codethepixel.com/codethepixel/public/cakephp-4-visualized-data-using-chartjs
- Author: Asyraf Wahi Anuar (https://codethepixel.com/codethepixel/public/author/asyraf-wahi-anuar)
- Published: 2022-04-02
- Category: CakePHP
- Tested with: CakePHP 4.x
- Tags: CakePHP, ChartJS, Chart, Graph, Data Visualization
- Reading time: 3 min

Visualizing data into charts is very useful to make the data more presentable and readable. Many free, open-source chart libraries are available for a developer to use, e.g. [ChartJS](https://www.chartjs.org/), [ApexCharts](https://apexcharts.com/), [D3.js](https://d3js.org/) and others. This tutorial will demonstrate how to count and visualize data in [CakePHP 4](https://cakephp.org/) using ChartJS. ChartJS is a free, open-source javascript library that supports various chart types, e.g., bar, pie, line, area, radar, scatter, and others. It is recommended to read the [ChartJS official documentation](https://www.chartjs.org/docs/latest/).

## Install ChartJS Using CDN

Load the following ChartJS CDN at the top of your page.

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
```

## Data Count/Sum and Visualized in ChartJS

Assuming that we have a user table that contains information related to title, category, status, hits (views) and created. From this information, we can:

### 1. Count total articles for each category \[tutorial, blog, project\] (Bar Chart)

The following codes are used to count the total of articles published in each category. Load the code into the controller.

```php
$this->set('count_tutorial', $this->Articles->find()->where('category' => 'tutorial')->count());
$this->set('count_blog', $this->Articles->find()->where('category' => 'blog')->count());
$this->set('count_project', $this->Articles->find()->where('category' => 'project')->count());
```

The above codes will provide the value for the total articles available in each of the categories. The value can be passed to ChartJS as shown below:

```javascript
<canvas id="articleCategory" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('articleCategory').getContext('2d');
var articleCategory = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Tutorial', 'Blog', 'Project'],
        datasets: [{
            label: '# of Category',
            data: [<?= json_encode($count_tutorial); ?>, <?= json_encode($count_blog); ?>, <?= json_encode($count_project); ?>],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            title: {
                display: true,
                text: 'Total Article in Each Category'
            },
        legend: {
                display: false,
                labels: {
                    color: 'rgb(255, 99, 132)'
                }
            },
        }
    },
});
</script>    
```

### 2. Count total articles for each status \[published, archived\] (Pie Chart)

The next example shows the code to count and sum the total articles based on the status, whether it is currently published or archived.

```php
$this->set('published', $this->Articles->find()->where('status' => '1')->count());
$this->set('archived', $this->Articles->find()->where('status' => '0')->count());
```

To generate the chart, passed the sum value to the ChartJS script as shown below:

```javascript
 <canvas id="articleStatus" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('articleStatus').getContext('2d');
var articleStatus = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['Published', 'Archived'],
        datasets: [{
            label: '# of Status',
            data: [<?= json_encode($published); ?>, <?= json_encode($archived); ?>],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            title: {
                display: true,
                text: 'Total Published/Archived Articles'
            },
        legend: {
                display: false,
                labels: {
                    color: 'rgb(255, 99, 132)'
                }
            },
        }
    },
});
</script> 
```

That's all. Happy coding :)
