DEV Community

Cover image for Visualize Data using chart.js library (Tutorial)
Sara °°°
Sara °°°

Posted on • Updated on

Visualize Data using chart.js library (Tutorial)

Sometimes in the software we build we find that we have to deal with data sets which cannot be viewed clearly unless we visualize it, we don't get the chance to have a bird-eye view to what's really happening in our project's data, here where comes the importance of Data visualization, using charts is one of the ways to visualize data.

" A chart can take a large variety of forms, however there are common features that provide the chart with its ability to extract meaning from data.

Typically the data in a chart is represented graphically, since humans are generally able to infer meaning from pictures quicker than from text. Text is generally used only to annotate the data.

One of the most important uses of text in a graph is the title. A graph's title usually appears above the main graphic and provides a succinct description of what the data in the graph refers to.

Dimensions in the data are often displayed on axes. If a horizontal and a vertical axis are used, they are usually referred to as the x-axis and y-axis respectively. Each axis will have a scale, denoted by periodic graduations and usually accompanied by numerical or categorical indications. Each axis will typically also have a label displayed outside or beside it, briefly describing the dimension represented. If the scale is numerical, the label will often be suffixed with the unit of that scale in parentheses. For example, "Distance traveled (m)" is a typical x-axis label and would mean that the distance traveled, in units of meters, is related to the horizontal position of the data within the chart. "

This blog is a tutorial on using the JS library chart.js.

Chart.js

Chart.js is a JavaScript open source library that allows you to draw different types of charts by using the HTML5 canvas element. Since it uses HTML5 canvas , you have to include a polyfill to support older browsers.
Its responsive, have Interactivity features (Mouse over - on click),and also use legend also known as a key. A legend contains a list of the variables appearing in the chart and an example of their appearance. This information allows the data from each variable to be identified in the chart.

Types of charts supported

Line Chart
Line Chart

Bar Chart
Bar Chart

Radar Chart
Radar Chart

Pie & Doughnut Charts
Doughnut & Pie Chart

Polar Area Chart
Polar Chart

Bubble Chart
Bubble Chart

Scatter Chart
Scatter Chart

Area Chart
Area Chart

Mixed: With Chart.js, it is possible to create mixed charts that are a combination of two or more different chart types.

How to use chart.js in your project

Below two examples, one with Dynamic data that is passed from a controller to a view via JSON. In second example data is fixed, not passed from anywhere.

Example (1) Data Passed from a controller

If we decided to use charts then we have some data sets, chart.js deals with data in form of data sets.

In the beginning include chart.js library to your project.
In example below, we used Ajax along with JSON object of lists to pass the data from a Controller called Charts to our view, it's up to you to decide how to send the data to the canvas. Or if Data is fixed then no need to JSON or Ajax just add data sets in form of fixed arrays/lists. Type of chart used is Doughnut.

Usually we will have 3 data sets that can be represented using an array or a list:

  1. Data set of the labels.
  2. Data set for the Quantity or value that represents each of the labels.
  3. Data set for the colors that represents each of the labels.

In controller, Method that process and send data from controller to view

[AllowCrossSiteJson]
    public ActionResult PieChartData()
    {
      List<string> labelsList = new List<string>();
      List<double> dataList = new List<double>();
      List<string> colorsList = new List<string>();

 //Add the code that process data from Database to be added to the three lists

    return Json(new { labelsList, colorsList, dataList }, JsonRequestBehavior.AllowGet);
        }

In View, add canvas tag that the chart will be displayed in later.

<canvas id="doughnut-chart" width="200" height="400"></canvas>


<div>
   <canvas id="doughnut-chart" width="200" height="400"></canvas>
   <script type="text/javascript">
      $(document).ready(function () {
      $.ajax({
      type: "get",
      //Charts is the controller
      // doughnutChartData is the Actionresult method that sends the JSON data                     to the view 
      url: "/Charts/doughnutChartData",
      dataType: 'json',
       //When success, data is the JSON object of lists passed from doughnutChartData method
      success: function (data) {
      //Making chart by using new Chart, and the canvas element with the id: doughnut-chart
             new Chart(document.getElementById("doughnut-chart"), {
               //Specify type of chart
                type: 'doughnut',
                data: {
               // First data set that contain labels, its accessed through JSON object data.
                labels: data.labelsList,
                datasets: [{
                label: "",
                //Second data set which contains a list of colors that will represent each label  
                backgroundColor: data.colorsList,
                 // Third data set which contains the value of each labe
                data: data.dataList
                        }]
                    },
                 // using Configuration Options, one can customize the chart, its explained below in a separate paragraph 
                options: {
                legend: {
                    display: false
                         },
                tooltips: {
                    enabled: true
                  },
                 maintainAspectRatio: false,
                 title: {
                    display: true,
                    text: 'Sales/ Item for Current Month'
                         }
                        }
                      });
           }, error: function (error) {
           console.log(error.responseText);
                                }
                                    });
                                });
    </script>
 </div>

In code above, first, the three data sets that represents our data was declared, and its ready to be displayed in the view, but making adjustments and customization can be done using Configuration options.

Configuration

The configuration is used to change how the chart behaves. There are properties to control styling, fonts, the legend, etc.

Global configuration

This concept was introduced in Chart.js 1.0 to keep configuration DRY, and allow for changing options globally across chart types, avoiding the need to specify options for each instance, or the default for a particular chart type.

Configuration options:

Animation

A number of options are provided to configure how the animation looks and how long it takes.

Layout

Padding. If this value is a number, it is applied to all sides of the chart (left, top, right, bottom). If this value is an object, the left property defines the left padding. Similarly the right, top and bottom properties can also be specified.

legend

The chart legend displays data about the datasets that are appearing on the chart.

Title

The chart title defines text to draw at the top of the chart.

Tooltip

Tooltips are the labels that appear when users hover over data points on your chart.

Elements

While chart types provide settings to configure the styling of each dataset, you sometimes want to style all datasets the same way. A common example would be to stroke all of the bars in a bar chart with the same colour but change the fill per dataset. Options can be configured for four different types of elements: arc, lines, points, and rectangles. When set, these options apply to all objects of that type unless specifically overridden by the configuration attached to a dataset.

Resulted Chart after applying code above:

When applying code Hovering over each color will display the label of each value.

Doughnut Chart

Example(2) Fixed Data


<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css">
</head>

<body>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});
</script>

</body>
</html>

Just Copy paste the second example and View result in your browser ;)

Further reading
Chart.js
Download chart.js
Configurations Options
Comparison of JavaScript charting libraries
Features of a chart

Latest comments (1)

Collapse
 
saraahmed626 profile image
Sara °°°

Thank you Vikas :)