Colorplotting 2D array plays a significant role in visualizing the elements of the array by giving color to each element so that we can distinguish between each element easily. We can also find out the maximum and minimum range of the array by plotting them with some color. Colorplotting might also come in handy to observe the patterns between the elements of the array.
The Matplotlib library is used for data visualization. It has several plot types suitable for different kinds of data.
In this tutorial, we will look at a comprehensive approach to using the color plot of the matplotlib library to color the 2D arrays.
First, we will learn about arrays, creating arrays using numpy, and generating random array elements. Following that, we will look at how to color plot these arrays.
What Is an Array?
An array is a collection of similar items that share a common name. The elements of the array should be of the same data type. As a result, we cannot make an array hold multiple different data types.
The indexing in an array starts from 0.
To access the elements of an array, we can use an integer that represents the element’s position in the array.
Check out this article to learn about arrays and creating multi-dimensional arrays using numpy.
An example of a two-dimensional array is given below.
#2d array import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print("The 2d array is:\n",arr)
We are using the numpy library to create a 2d array. Hence, we are importing the library as np in the second line.
A variable called arr is initialized to store the array after creation.
Lastly, we are printing the array using the print() function.
Creating 2D Arrays Using Random Function
In the previous example, we have seen how to create an array using the numpy library, where the user specifies the elements of the array. How about we leave the generation of the elements of an array to the computer?
We can make the computer generate random elements of the array with the help of
Not quite familiar with the random function? Check out this post to know more about it.
Let us see how we can do that.
import numpy as np a=np.random.rand(5,5) print("The randomly generated 2d array is:\n",a)
As usual, we are importing the numpy library to work with arrays.
We are creating a variable called a to store the elements of the array that are randomly generated by the random function.
np.random.rand(5,5) says that we will generate an array that contains five rows and five columns of randomly generated values.
Every time you run this code, you will get different outputs where the elements are equally distributed between 0 and 1.
Lastly, we are printing the array.
Now that we have a clear idea about the arrays and how to create arrays using the numpy library and the random function, let us dive into color plotting these arrays!
What Is a Colormap?
Before we move on to the color plotting, we first need to be clear with the concept of colormaps. As self-describing as it sounds, a colormap is defined as a mapping between a range of values and colors to visualize the data.
ColorPlotting 2D Arrays
We can use the methods of the matplotlib to color plot arrays we created. We will try different approaches to plot the arrays, which might help in data interpretation.
The approaches we are going to use are:
- Creating a color plot using the binary colormap(for black & white plot)
- Creating a color plot using pcolormesh()
- Creating a color plot using PuBuGn
- Creating a color plot using dimensions and colors
ColorPlotting 2D Array Using the Binary Colormap
The binary colormap plots the array with only two colors typically black and white, While one color represents one end of values(highest or lowest), the other represents the other end of the values. This representation might vary based on the data used for visualization. The binary colormap is customizable. That is, the binary color map can be used to plot the arrays in black and white and any other two colors.
Let us see the code and understand how to use binary colormap.
#using the binary colormap import matplotlib.pyplot as plt import numpy as np a = np.random.rand(5,5) print("The array is :\n",a) print("*"*15) print("The highest value in the array:",np.max(a)) print("The lowest value in the array:",np.min(a))
In the second and third lines, we import the matplotlib and numpy libraries to visualize and create arrays.
In the third line, we are initializing a variable ‘a’ to store the 5×5 array that contains randomly generated values.
In the following line, we are printing the array.
print("*"*15): This line is a separator and prints 15 asterisks to the screen.
In the last two lines, we are printing the maximum and minimum values present in the array just to check which color represents what range.
The array is given below.
Let us see how we can plot the arrays.
The code is given below.
#plotting the array plt.imshow(a, cmap='binary') plt.colorbar() plt.show()
Here is the breakdown of the code.
The imshow() method of the matplotlib is used to display the plot or graph as an image. The array a is passed as the first argument of this method. The camp stands for colormap and the colormap we used here is binary—the binary colormap, by default, plots the data in black and white.
The colorbar() method is used to describe the colors given for the value in the array.
Lastly, the show method is used to display the plot. This method works more or less like print().
The plot is shown below.
Observe the array and its maximum and minimum values. The maximum value in the array is 0.9941… which is present in the second row and first column. Now observe the plot. This element is situated at the [1,0] grid. Black color is used to represent the maximum value.
The minimum value in the array is 0.0362, situated at the third-row fourth column. This element is located at the [2,3] grid in the plot. We can say that white is used to represent the minimum value.
Various shades of grey represent all the other values in the range of 0.0362 and 0.9941.
ColorPlotting 2D Array Using the pcolormesh
The pcolormesh function of the matplotlib library is used to create a pseudocolor plot of a non-regular rectangular grid. Pseudocoloring is the process of giving a very less number of colors to plot the elements of the array or any data.
Let us see how we can use pcolormesh on the 2D array.
The code is given below.
import matplotlib.pyplot as plt import numpy as np data = np.random.rand(5,5) plt.pcolormesh(data, cmap='viridis') plt.colorbar() plt.show()
As usual, we import the matplotlib and numpy libraries to visualize and create arrays.
Next, we are creating an array called data to create an array that contains 25 randomly generated arrays spread in a 5×5 array.
In the following line, we are using the pcolormesh of the matplotlib library to take the data as the first argument, and the colormap we used here is viridis.
viridis is a collection of colors ranging from dark purple to light yellow.
The colorbar is used to describe the colors given to the elements of the array.
The show method is used to display the plot.
ColorPlotting 2D Array Using the PuBuGn Colormap
The PuBuGn colormap of the matplotlib plots the data with three colors- Purple, Blue, and, Green. It is a sequential colormap that starts plotting with various shades of Purple, changes to Blue, and lastly to Green.
Let us see how we can use this color map.
import numpy as np from matplotlib import pyplot as plt data = np.random.rand(5,5) plt.imshow(data, cmap='PuBuGn') plt.colorbar() plt.show()
We have imported the matplotlib and numpy libraries in the first two lines.
We are creating a data variable to store an array of 25 randomly generated values.
The imshow() method of the matplotlib library displays the plot as an image. It takes the array as the first argument and the camp as the second.
The colorbar method is used to describe the colors given to the values.
The show method is used to display the plot.
ColorPlotting 2D Arrays With Dimensions
All the above examples we saw earlier are dimensionless. This might not look good when working on big projects. Having uniform dimensions makes the plot looks good and professional.
import numpy as np from matplotlib import pyplot as plt c = np.random.rand(5,5) plt.rcParams["figure.figsize"] = [6.4,4.8] plt.rcParams["figure.autolayout"] = True img = plt.imshow(c, cmap="magma") plt.colorbar(img) plt.show()
The first and second lines import the numpy and matplotlib libraries to create and visualize arrays.
A variable called c is created to store the 2D array generated by the random function.
rcParams method of the matplotlib library is used to set the plot’s figure size, width, and height. The default is 6.4 inches wide and 4.8 inches tall.
The same method is also used to set the adjustment of the figure to true. This means the layout is automatically updated based on the figure size and dimensions.
The imshow is used to display the plot as an image. The colormap we have used here is magma.
magma is a beautiful collection of colors from dark purple to light orange.
The show() method is used to display the plot.
Here is a chart from the official matplotlib documentation of some of the sequential colormaps you can use as a replacement for the colormaps used in the above examples.
To conclude, we have seen what an array is and how we can generate the elements of the array with the help of NumPy’s very own method called random.
We have understood the definition of color maps and how color maps can be useful in visualizing data and in this case, elements of a 2D array.
Next, we have seen various approaches to color plotting 2D arrays with randomly generated elements.
Firstly, we have seen the usage of the binary color map that plots with only two colors. In this tutorial, we have used black and white. As observed from the output, black represents the maximum values of the array and white represents the minimum value of the array. Any element between these two values is represented by a shade of grey.
Next, we have seen the usage of pcolormesh to implement the color plot. The pcolormesh of the matplotlib uses a few colors to plot the data. This helps us get a deeper understanding of the data patterns.
The following approach uses PuBuGn colormap which stands for Purple-Blue-Green. It is a sequential colormap that starts plotting with various shades of Purple, changes to Blue, and lastly to Green.
The last approach is no different from the above examples. But, we specify the dimensions of the plot that is displayed. The
rcParams of the matplotlib is used to define the dimensions of the plot.
You can explore the features of the matplotlib through this official documentation.