Thursday, April 20, 2017

Getting Started With Chart.js: Radar and Polar Area Charts

Getting Started With Chart.js: Radar and Polar Area Charts

The previous tutorial of this series focused on creating line and bar charts using Chart.js. Both these charts have their own uses and configuration options that were covered in detail in the last tutorial.

In this tutorial, you will learn about two new chart types that can be created using Chart.js: radar and polar area charts. Just like the previous tutorial, we will start with a brief overview of the chart types and then move to a more detailed discussion. 

Creating Radar Charts

Line and bar charts are useful when you want to compare only one or two properties of a large number of objects—for example, the population of all the countries in Asia or the number of different pollutants in the atmosphere.

Let's say you want to compare the density, opacity, viscosity, refractive index and boiling point of only three different liquids. Creating a bar chart for this data will be problematic as you will need to create five different columns for each liquid. It will also be hard to compare the corresponding properties of the liquids. 

In situations where you have to compare a lot of properties of only a few objects, creating a radar chart is the most efficient method of visualizing and comparing data. These charts are also known as spider charts.

From Wikipedia, a radar chart is a graphical method of displaying multivariate data in the form of a two-dimensional chart of three or more quantitative variables represented on axes starting from the same point. The relative positions and angles of the axes are typically uninformative. 

Let's create our first radar chart now. Radar charts are created by setting the type key in Chart.js to radar. Here is a very basic example.

Let's plot the marks of two students of a class in five different subjects. Here is the code to provide the data for creating the chart.

The first chart that we usually create does not have any background color specifically set by us. However, radar charts can have a lot of overlap, making it difficult to correctly identify the data points without any color coding. 

For this reason, a color has been assigned to each dataset using the backgroundColor key. The following demo shows the final result of our code. As you can see, it is now very easy to compare the performance of both students in different subjects.

Besides the background color, you can also change the border color and border width for the chart using the borderColor and borderWidth keys. It is also possible for you to create dashed borders instead of continuous lines using the borderDash key. This key accepts an array as its value. 

The first element of the array determines the length of the dashes, and the second element determines the space between them. You can also provide an offset value for drawing the dashes using the borderDashOffset key.

You can also control the border color and width for plotted points using the pointBorderColor and pointBorderWidth. Similarly, you can also set a background color for different points using the pointBackgroundColor key. The size of the plotted points can be specified using the pointRadius key. You can control the distance at which the points should start interacting with the mouse using the pointHitRadius key.

You can also control the appearance of the plotted points on hover using the pointHoverBackgroundColor, pointHoverBorderColor and pointHoverBorderWidth keys. One thing that you need to remember is that these hover keys will not wait for you to actually hover over the element to get triggered. The changes will take effect as soon as you are inside the hit radius set above.

There are a lot of shapes available for plotted points. They are circular by default. However, you can change the shape to triangle, rect, rectRounded, rectRot, cross, crossRot, star, line, and dash. 

Let's use all these keys to redraw the previous radar chart. Here is the code to provide configuration options for the datasets and the scales.

Inside the chartOptions object, the min and max values are used to set the minimum and maximum values for the scale. The stepSize key can be used to tell Chart.js the number of steps that it should take to go from min to max. Here is the final result of the above code.

Creating Polar Area Charts

Polar area charts are similar to pie charts. Two major differences between these charts are that in polar area charts all the sectors have equal angles and the radius of each sector depends on the plotted value. These charts are used to plot cyclic phenomena. For example, you can use it to plot the number of migratory birds of a given species in your area in each season of the year.

The radius of each sector in these charts is proportional to the square root of the number of corresponding objects. In the case of migratory birds, the radius will be proportional to the square root of the number of birds in your area.

You can create polar area charts in Chart.js by setting the type key to polarArea. Here is the basic code that you need to create a polar chart.

Here is the code to plot the number of migratory birds on a polar area chart. The only data provided at this point is the number of birds and the background color for different seasons.

The above code will create the following polar area chart.

The polar area chart provides the usual options to set the backgroundColor, borderWidth, borderColor, hoverBackgroundColor, hoverBorderWidth, and hoverBorderColor. There are also some polar area chart specific keys that you can use to customize their appearance. 

For example, you can set the starting angle for the first value in the dataset using the startAngle key. Similarly, the lineArc key that can be found under scale can be used to specify if the lines drawn should be circular or not by setting its value to true or false respectively.

The sectors drawn in the polar area chart are both rotated and scaled by default. However, you can prevent the scaling animation by setting the value of the animateScale key to false. Similarly, the rotating animation can be turned off by setting the value of the animateRotate key to false. Both these keys are available under animation. 

The code below changes the value of a few keys to make the chart more visually appealing.

Besides rotating the chart and disabling the rotation animation, we have also moved the legend to the left of the chart by setting the value of position to left. This leaves enough space at the top of the chart to display it properly.

Final Thoughts

In this tutorial, you learned about the applications of radar and polar area charts. After that, you learned how to create basic charts and customize them with various configuration options available in Chart.js. You will learn about pie and bubble charts in the next part of the series. 

If you're working with the web, especially on the front-end, JavaScript is important to know. Of course, it's not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

If you have any questions about this tutorial, please let me know in the comments.


How to Create a Bold, Cartoonish Text Effect in Adobe Illustrator

How to Work With MVPs (Minimum Viable Products)

Wednesday, April 19, 2017

How to Set Up a Project in Angular 2

How to Add Wings to a Photo in Adobe Photoshop

Quick Tip: Working With Custom Fonts in Android O

Working With PHP Arrays in the Right Way

Working With PHP Arrays in the Right Way

In this tutorial, I am going to make a list of common PHP array functions with examples of usage and best practices. Every PHP developer must know how to use them and how to combine array functions to make code readable and short.

Also, there is a presentation with given code examples, so you can download it from the related links and show it to your colleagues to build a stronger team.

The Basics

Let's start with the basic functions that work with array keys and values. One of them is array_combine(), which creates an array using one array for keys and another for its values:

You should know, that the function array_values() returns an indexed array of values, array_keys() returns an array of keys of a given array, and array_flip() exchanges keys with values:

Make Your Code Shorter

The function list(), which is not really a function, but a language construction, is designed to assign variables in a short way. For example, here is a basic example of using the list() function:

This construction works perfectly with functions like preg_slit() or  explode() . Also, you can skip some parameters, if you don't need them to be defined:

Also, list() can be used with foreach, which makes this construction even better:

With the extract() function, you can export an associative array to variables. For every element of an array, a variable will be created with the name of a key and value as a value of the element:

Be aware that extract() is not safe if you are working with user data (like results of requests), so it is better to use this function with the flags EXTR_IF_EXISTS and EXTR_PREFIX_ALL.

The opposite of the previous function is the compact() function, which makes an associative array from variables:

Filtering Functions

There is a great function for array filtering, and it is called array_filter(). Pass the array as the first param and an anonymous function as the second param. Return true in a callback function if you want to leave this element in the array, and false if you don't:

There is a way to filter not only by the values. You can use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH as a third parameter to pass the key or both value and key to the callback function.

Also, you can call array_filter() without a callback to remove all empty values:

You can get only unique values from an array using the array_unique() function. Notice that the function will preserve the keys of the first unique elements:

With array_column(), you can get a list of column values from a multi-dimensional array, like an answer from a SQL database or an import from a CSV file. Just pass an array and column name:

Starting from PHP 7, array_column() becomes even more powerful, because it is now allowed to work with an array of objects. So working with an array of models just became easier:

Walking Through the Arrays

Using array_map(), you can apply a callback to every element of an array. You can pass a function name or anonymous function to get a new array based on the given array:

There is a myth that there is no way to pass values and keys of an array to a callback, but we can bust it:

But this looks dirty. It is better to use array_walk() instead. This function looks the same as array_map(), but it works differently. First of all, an array is passed by a reference, so array_walk() doesn't create a new array, but changes a given array. So as a source array, you can pass the array value by a reference in a callback. Array keys can also be passed easily:

Joining the Arrays

The best way to merge two or more arrays in PHP is to use the array_merge() function. Items of arrays will be merged together, and values with the same string keys will be overwritten with the last value:

To remove array values from another array (or arrays), use array_diff(). To get values which are present in given arrays, use array_intersect(). The next examples will show how it works:

Do the Math With Array Values

Use array_sum() to get a sum of array values, array_product() to multiply them, or create your own formula with array_reduce():

To count all the values of an array, use array_count_values(). It will give all unique values of a given array as keys and a count of these values as a value:

Generating Arrays

To generate an array with a given size and the same value, use array_fill():

To generate an array with a range in of keys and values, like day hours or letters, use range():

To get a part of an array—for example, just the first three elements—use array_slice():

Sorting Arrays

It is good to remember that every sorting function in PHP works with arrays by a reference and returns true on success or false on failure. There's a basic sorting function called sort(), and it sorts values in ascending order without preserving keys. The sorting function can be prepended by the following letters:

  • a, sort preserving keys
  • k, sort by keys
  • r, sort in reverse/descending order
  • u, sort with a user function

You can see the combinations of these letters in the following table:

a k r u
a asort
arsort uasort
k ksort krsort
r arsort krsort rsort
u uasort
usort

Combining Array Functions Like a Boss

The real magic begins when you start to combine array functions. Here is how you can trim and remove empty values in just a single line of code with array_filter() and array_map():

To create an id to a title map from an array of models, we can use a combination of array_combine() and array_column():

To get the top three values of an array, we can use array_count_values(), arsort(), and array_slice():

It is easy to use array_sum() and array_map() to calculate the sum of order in a few rows:

Conclusion

As you can see, knowledge of the main array functions can make your code much shorter and more readable. Of course, PHP has many more array functions, and even the given functions have many variations to use with extra parameters and flags, but I think that in this tutorial we've covered the basics that every PHP developer should know.

Please note that I've created a presentation with the given examples, so you can download it from the related links and show it to your team.

If you have any questions, don't hesitate to ask them in the comments to the article. 

Further Reading and Related Links