Display line and area charts in PHP and MySQL
Most data in any web application is usually sourced from a database. Usually some data transformation is required before we can visualize the required data. Most programmers however wanting to display visualizations or charts shy away from the task as there are a number of intermediate steps required to display the visualization. Morris charts however makes the task easier. We only need to directly pass the MySQL queried rows to the Morris charts javascript and we are done. Morris Charts is one of my favorite tools to display dashboard visualization on the web.
Let us see with a simple example. But first go ahead and download the library.
Example
Our first example will show how to display a line chart. Line charts are usually used to display temporal data over time. The following is a sample CRON log MySQL table used to illustrate the examples. The table is used in one of my web applications to record CRON execution times. Every hours some images are processed by the CRON job which is then recorded in the database table.
First include the stylesheets and script files in the header. Adjust the paths according to your directory structure or directly link to a CDN as shown below. Morris depends on the Raphael library to render graphics. However, if you use the CDN path as given below you do not need to download anything.
In the following code example I will display the last 24 CRON execution timings as a line chart. First we will get the data from MySQL.
The
$rows
variable now contains the data array which will be used to display the line chart. The array will be like the following:
The data is used below to display the chart. Note we need to encode the data to json before we pass it to Morris charts. Morris charts expects the data as a JSON array.
Next we define a div where we want to display the chart.
This will display the line chart as below.
If you need to plot another variable then you can add the same to the javascript data option. Say we need to add a column from the db table like ‘images_failed’ to the graph, we can do the it as below.
This will display the 2 variable line chart.
We can also display the above as a area chart by changing the javascript function name from ‘Morris.Line’ to ‘Morris.Area’. This will display the following without changing any other option.
There are a variety of options to customize the charts.
0 comments :