In MATLAB, a colormap is a matrix containing a range of colors used to represent data in various visualizations, such as images, surface plots, and scatter plots. It’s a built-in function that allows users to specify which colormap they want to use for their visualizations or to retrieve information about the current colormap.
A custom colormap is a user-defined color scheme that can be applied to different MATLAB or other visualizations. MATLAB has some predefined colormaps, a few of which are:
jet
: These are rainbow colormaps for smooth transitions across colors, commonly used for continuous data.hot
: These emphasize high-intensity colors like red and yellow, fading to black, often used for highlighting.cool
: These start with dark blue and transition to lighter blues, representing decreasing intensity, suitable for lower values or creating a calming effect.We can define multiple colormaps for our visualizations. It requires defining a matrix where each row represents a color, with the values for red, green, and blue intensity ranging from 0
to 1
. Follow the steps below to create a custom colormap:
Define a custom colormap matrix as follows:
Each row of the matrix represents a color.
Each column represents the intensity of red, green, and blue.
Values should range from 0
to 1
.
Set the custom colormap for the figure using the colormap()
function.
Let’s review an example that shows how to create and use a custom colormap in the code widget below.
% Define a custom colormap matrixcustom_colormap = [0.2, 0.4, 0.6; % RGB values for the first color0.8, 0.1, 0.2; % RGB values for the second color0.0, 0.7, 0.3 % RGB values for the third color];a = figure();[X,Y,Z] = peaks(100);surf(X,Y,Z);colorbar; % Add a colorbar to see the effect of the colormap% Set the custom colormapcolormap(custom_colormap);
In the code above:
Lines 2-6: Create a matrix with different RGB values, where each row shows separate RGB values for each color.
Line 8: It creates a new figure window and assigns it to the variable a
.
Line 9: It generates data using the peaks()
function, which creates a sample surface dataset with peaks and valleys. It generates a grid of points with coordinates (X, Y)
and corresponding elevation values Z
. The argument 100
specifies the number of points in each dimension.
Line 10: It creates a surface plot of the data generated in the previous step. It visualizes the surface described by the (X, Y, Z)
coordinates.
Line 11: It adds a colorbar
to the current plot. The colorbar
helps to interpret the colors used in the plot, indicating the correspondence between the color and data value. Here, it shows the color mapping applied to the surface plot created in the previous step.
Line 13: It creates a custom colormap based on the matrix we defined earlier.
Free Resources