Learn Python, Microsoft 365 and Google Workspace
Connect with me: Youtube | LinkedIn | WhatsApp Channel | Web | Facebook | Twitter
To access the updated lecture notes, please click on the following link: https://yasirbhutta.github.io/matlab/docs/graphics.html
The xlabel() and ylabel() functions are used to label the x and y axes in a figure in MATLAB. The labels should describe the data that is being plotted on each axis.
The title() function is used to add a title to a figure in MATLAB. The title should provide a brief description of the plot.
Example #: Label the axes and add a title
x = linspace(0, 10, 100);
y = sin(x);
plot(x, y);
xlabel('X-axis');
ylabel('Y-axis');
title('Sine Wave');
The grid() function is used to add grid lines to a figure in MATLAB. Grid lines can help to make it easier to interpret the data in a plot.
Example #:
years = [1990, 1995, 2000, 2005, 2010, 2015, 2020];
co2_emissions = [26.17, 26.61, 26.89, 27.46, 28.12, 29.08, 29.94];
plot(years,co2_emissions,"ro-");
title("Global CO2 Emissions from 1990 to 2020.");
xlabel("Years");
ylabel("CO2 Emissions (Billion metric tons per year");
grid on;
box off;
See also:
he axis() function is used to set the limits of the axes in a figure in MATLAB. The axes are the horizontal and vertical lines that extend across the figure window.
The plot() function is used to create a line plot in MATLAB. A line plot is a graphical representation of a set of data points connected by a line.
The hold function is used to prevent MATLAB from overwriting existing plots when creating new ones. By default, MATLAB overwrites existing plots when creating new ones. However, if you use the hold function before creating a new plot, MATLAB will add the new plot to the existing plot instead of overwriting it.
Example # Plotting multiple lines on the same graph
x = linspace(0, 10, 100);
y1 = sin(x);
y2 = cos(x);
plot(x, y1, 'b');
hold on;
plot(x, y2, 'r');
hold off;
This will plot two lines on the same graph, one blue and one red. The hold on and hold off functions are used to prevent the second line from overwriting the first line.
Example #1:
x = 1:1:10;
y1 = sqrt(x.^2+1);
y2 = 2 * x + 20;
y3 = 3 * x + 3;
plot(x,y1,'r*:');
line(x,y2);
line(x,y3);
Example #2: Plotting Two Functions on the Same Graph in MATLAB
x = 1:1:10;
y1 = sqrt(x.^2+1);
y2 = 2 * x + 20;
plot(x, y1, 'r', x, y2, 'bo');
axis([0 12 0 45]);
The legend() function is used to create a legend for a figure in MATLAB. A legend is a key that explains which line or curve corresponds to which data set.
Example #1:
% Real world data example
% Global average temperature data from NASA
% https://data.giss.nasa.gov/gistemp/graphs/
% Load the data
data = load('global_average_temperature.csv');
% Extract the years and temperatures
years = data(:, 1);
temperatures = data(:, 2);
% Create a line plot of the data
figure;
plot(years, temperatures);
% Add a legend
legend('Global average temperature');
% Set the axis labels and title
xlabel('Year');
ylabel('Temperature (°C)');
title('Global Average Temperature from 1880 to 2022');
Example #1: Visualizing Daily Temperature Data with Subplots in MATLAB
Download dataset Daily Temperature (Dataset #2)
from Datasets.
% Specify the name of the CSV file
filename = 'ds2.csv';
% Read the data from the CSV file into a table variable
data = readtable(filename,'VariableNamingRule','preserve');
% Create the first subplot
subplot(1, 2, 1);
plot(data.dated, data.temperature);
title('Daily Temperatures');
xlabel('Date');
ylabel('Temperature (C)');
% Create the second subplot
subplot(1, 2, 2);
histogram(data.temperature);
title('Temperature Distribution');
xlabel('Temperature (C)');
ylabel('Frequency');
% Save the figure
saveas(gcf, 'daily_temperatures.png');
Example #1: Plotting a bar graph
x = categorical({'A', 'B', 'C'});
y = [10, 20, 30];
bar(x, y);
Categorical Arrary: categorical is a data type to store data with values from a finite set of discrete categories. For example, the syntax C = categorical({‘R’,’G’,’B’,’B’,’G’,’B’}) creates a categorical array with six elements that belong to the categories R, G, or B.[^1]
Download dataset Population by Country
from Datasets.
Example #2: Population Distribution by Country using bar charts
% Specify the name of the CSV file
filename = 'ds1.csv';
% Read the data from the CSV file into a table variable
data = readtable(filename,'VariableNamingRule','preserve');
% Convert the Country column to a categorical variable
x = categorical(data.Country);
% Generate a bar plot of the population data
bar(x,data.Population);
% Add a title and axis labels to the plot
title('Population by Country');
xlabel('Country');
ylabel('Population');
See also:
See also:
A histogram is a data visualization tool that shows the frequency distribution of numerical data. It is a type of bar graph that displays the number of data points that fall within each of a series of intervals called bins. The bins are usually specified as consecutive, non-overlapping intervals of a variable. The height of each bar in the histogram represents the number of data points that fall within that bin.
Image Source: https://www150.statcan.gc.ca/n1/edu/power-pouvoir/ch9/histo/5214822-eng.htm
Histograms are useful for visualizing the distribution of data, such as the distribution of heights of students in a class, the distribution of test scores, or the distribution of the time it takes to complete a task. They can also be used to compare the distributions of two or more datasets.
Here are some of the key features of a histogram:
Example #1: Plotting a histogram
x = randn(1000, 1);
histogram(x);
See also:
Example #:1 Plotting a pie chart
X = [10 20 30];
pie(X);
This will plot a pie chart with three slices, one for each value in the vector X. The size of each slice represents the proportion of that value to the total.
Example #2 Visualizing Fruit Sales Distribution with Exploded Pie Chart
% Define the fruit names and sales figures
fruit_names = ["Apples", "Oranges", "Bananas", "Grapes", "Strawberries"];
sales_figures = [120, 90, 150, 80, 60];
% Define the explode vector to offset the "Bananas" slice
explode = [0 0 1 0 0];
% Create the pie chart and label the slices
pie(sales_figures, explode, fruit_names);
% Set the title of the pie chart
title('Fruit Sales Pie Chart');
See also:
Example #1 Create 3-D Bar Graph from Vector Data
% Create a vector of values to plot.
z = [50 40 30 20 10];
% Plot the 3-D bar graph.
bar3(z);
% Set the axes labels.
xlabel('X Axis');
ylabel('Y Axis');
zlabel('Z Axis');
% Set the title.
title('My 3-D Bar Graph');
See also:
See also:
In MATLAB, the meshgrid function is used to create two matrices from two vectors
. Each element of the first matrix represents one value from the first vector, and each element of the second matrix represents one value from the second vector. This is useful for creating grids of data points
, which can then be used for plotting or other calculations.
Example #1:
x = linspace(1,3,3);
y = linspace(2,10,5);
[X,Y] = meshgrid(x,y);
disp(X);
disp(Y);
Explanation:
Output:
X =
1 2 3
1 2 3
1 2 3
1 2 3
1 2 3
Y =
2 2 2
4 4 4
6 6 6
8 8 8
10 10 10
Application of meshgrid:
Calculus: In calculus, particularly in multivariable calculus, the concept of a surface is used when dealing with functions of two variables. The graph of a function of two variables (such as z = f(x, y)) can be thought of as a surface in three-dimensional space.
Example #1:
x = -3:0.1:3;
y = x;
[X,Y] = meshgrid(x);
F = X.^2 + Y.^3;
mesh(X,Y,F);
Example #2:
x = linspace(0,10,20);
y = linspace(-5,5,30);
[X,Y] = meshgrid(x,y);
% Example function: Z = sin(x)*cos(y)
Z = sin(X).*cos(Y);
% Plot the mesh using the generated X, Y, and Z matrices
mesh(X, Y, Z);
% Customize the plot with labels, title, and colormap
xlabel('X');
ylabel('Y');
zlabel('Z');
title('Mesh Plot of sin(x)*cos(y)');
colormap('jet');
colormap(‘jet’): Set the colormap to ‘jet’ for a visually appealing gradient.
Example #3: Plot quadric surface with the equation yz=1
% Define the grid
[x, y] = meshgrid(-10:0.1:10, -10:0.1:10);
% Define the height of the surface
z = 1./y;
% Create the surface plot
mesh(x, y, z);
% Set axis labels
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
% Set the view for better visualization
view(45, 30);
% Title of the plot
title('Quadric Surface: yz = 1');
% Set color map
colormap("cool");
% Display a colorbar
colorbar;
See also:
Example #1:
x = -3:0.1:3;
y = x;
[X,Y] = meshgrid(x);
F = X.^2 + Y.^3;
surf(X,Y,F);
Example #2:
x = -3:0.1:3;
y = x;
[X,Y] = meshgrid(x);
F=sqrt(X.^2 + Y.^2)
surf(X,Y,F);
Example #3: 3D Surface Plot with Gaussian Function
% Create a grid of x and y values
[x, y] = meshgrid(-5:0.1:5, -5:0.1:5);
% Define a function for the surface (example: a 3D Gaussian)
z = exp(-(x.^2 + y.^2) / 5) .* sin(x) .* cos(y);
% Create the surf plot
figure;
surf(x, y, z);
% Customize the plot
title('3D Surface Plot with Gaussian Function');
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
colormap('parula'); % You can change the colormap
colorbar; % Display colorbar
% Optionally, add additional features like grid and rotate the plot
grid on;
rotate3d on;
Example #4: Saddle-Shaped Surface Plot
x = -10:0.2:10;
y = x;
% Define a grid of X and Y values
[X, Y] = meshgrid(x);
% Define a function for the surface (e.g., a saddle-shaped surface)
Z = 0.1 * (X.^2 - Y.^2);
% Create a 3D surface plot
surf(X, Y, Z);
% Add labels and a title
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Saddle-Shaped Surface Plot');
% Display a color bar and change the color.
colorbar;
colormap("cool");
Output:
Example #5: 3D surface plot of the cone
x = -10:0.2:10;
y = x;
% Define a matrix of X and Y values
[X, Y] = meshgrid(x);
% Define the surface function for a cone
Z = sqrt(X.^2 + Y.^2);
% Create a 3D surface plot of the cone
surf(X, Y, Z);
% Add labels and a title
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Cone Surface Plot');
% Display a color bar and change the color.
colorbar;
colormap("cool");
Example #6: Create a 3D surface plot of the hyperboloid
x = -10:0.2:10;
y = x;
% Define a matrix of X and Y values
[X, Y] = meshgrid(x);
% Define the surface function for a hyperboloid
Z = X.^2 + Y.^2 - 1;
% Create a 3D surface plot of the hyperboloid
surf(X, Y, Z);
% Add labels and a title
xlabel('X-axis');
ylabel('Y-axis');
zlabel('Z-axis');
title('Hyperboloid Surface Plot');
% Display a color bar and change the color.
colorbar;
colormap("cool");
Example #7: 3D Cone Using surf and meshgrid
This method involves creating two matrices, one for the radius of the cone at different heights and another for the angle. Then, you use meshgrid to combine these matrices into 3D grids and use surf to plot the surface.
r = linspace(0, 1, 50);
th = linspace(0, 2*pi, 50);
[theta,z] = meshgrid(th,r);
radius = 1 - z;
x = radius .* cos(theta);
y = radius .* sin(theta);
surf(x, y, z);
title("3D cones");
xlabel("x axis");
ylabel("y axis");
zlabel("z axis")
See also:
Example #
[X,Y] = meshgrid(-2:.2:2,-2:.2:3);
Z = X.*exp(-X.^2-Y.^2);
contour(X,Y,Z);
colormap jet;
Example #
[X,Y] = meshgrid([-2:.25:2]);
Z = X.*exp(-X.^2-Y.^2);
contour3(X,Y,Z,30)
surf(X,Y,Z)
view(-15,25);
colormap cool;
Example # Plot quadric surface with the equation x^2 + 4*y^2
% Generate meshgrid
[X, Y] = meshgrid(-2:0.1:2, -1:0.1:1);
% Calculate z values based on the function
Z = X.^2 + 4*Y.^2;
% Create the surface plot
surf(X, Y, Z);
% Set axis labels and title
xlabel('X');
ylabel('Y');
zlabel('Z');
title('Quadric Surface: x^2 + 4*y^2');
% Adjust lighting and shading for better visualization
lighting gouraud;
shading interp;
% Rotate the plot for a better view (optional)
view(45, 20);
% Define the cylinder parameters
[X, Y, Z] = cylinder(50, 20);
% Create surface plot
surf(X, Y, Z);
This code will create a cylinder with a height of 20 and a radius of 50. The cylinder function generates a 3D array of points that represent the surface of the cylinder. The surf function then plots the surface using these points.
See also:
Which of the following functions is used to create a plot of a line?
Which of the following functions is used to create a plot of a bar graph?
Which of the following functions is used to create a plot of a pie chart?
Which of the following is NOT a valid MATLAB graphics command?
What is the purpose of the title() function?
How can you create a subplot in MATLAB?
What is the difference between a bar plot and a histogram?
Which of the following is NOT a valid MATLAB graphics function?
Which of the following is the correct syntax for plotting a line graph of the function y = x^2?
What is the purpose of the legend() function?
What is the purpose of the xlabel() and ylabel() functions?
Which of the following commands would you use to change the title of the current figure to ‘My Figure’?
What is the command to create a 2-D line plot of x and y vectors in MATLAB?
What is the command to create a pie chart of a vector x in MATLAB?
Which MATLAB function is used to label the axes of a figure?
What is the command to show the box outline around the axes in MATLAB?
What is the command to show the grid in a MATLAB figure?
Which MATLAB function is used to add text to a plot?
How can you change the font color of the text in a plot?
Code snippet:
x = 1:10;
y = 1:10;
plot(x, y);
text(6, 5, 'string', 'color', 'red');
How can you position text relative to a specific data point in a plot?
What is the primary purpose of the
hold
function in MATLAB plotting?
Which of the following statements correctly describes the behavior of the
hold
function when used in conjunction with the plot function?
Which of the following scenarios would require the use of the
hold
function?
What are the two basic arguments required for the
plot()
function?
What is the default line style used by the
plot()
function?
What is the default line color used by the
plot()
function?
Which line style is represented by the string ‘-.’?
What is the purpose of using different line styles in a plot?
How would you set the line style of a plot to be dashed?
How would you create a plot with two lines, one solid and one dashed?
What is the default marker style for a line plot in MATLAB?
How can you add a colorbar to a surface plot created with surf in MATLAB?
- Using the color function
- Using the colorbar function
- By specifying a colormap argument in surf
- Both b and c
When generating a surface plot with surf, which of the following options provides information about the color values used?
- The function arguments within surf
- The axis labels automatically generated
- The legend displayed by default
- The colorbar function specifically designed for this purpose
What is the purpose of the meshgrid() function when creating 3D plots in MATLAB?
- It generates a grid of points for plotting 2D data.
- It generates a mesh for 3D surface plots.
- It creates a color map for 3D plots.
- It calculates the gradient of a function.
Which function is used to customize the appearance of a 3D plot, such as changing colors?
- colorplot
- customize3D
- colormap
- plot3D
Which function in MATLAB is used to add labels and titles to a 3D plot?
- xlabel(), ylabel(), zlabel(), title()
- legend()
- text()
- annotation()
Which MATLAB function is used to create 3D histograms or bar plots?
- hist()
- bar3()
- histogram()
- bar()
Which function is used to create multiple 3D plots in the same figure window?
- subplot()
- figure()
- hold()
- plot3()
plot()
function in MATLAB?grid()
function in MATLAB?axis()
function in MATLAB?xlabel()
and ylabel()
functions in MATLAB?title()
function in MATLAB?legend()
function in MATLAB?Answer:
The line function is used to create a line plot in MATLAB. The syntax for the line function is as follows:
line(x, y)
where x is a vector of x-coordinates and y is a vector of y-coordinates.
plot
function?Answer:
To plot a line in MATLAB, you can use the plot() function. The plot() function takes two vectors as arguments: the x-values and the y-values. For example, the following command will plot a line with x-values from 1 to 10 and y-values from 1 to 10:
x = 1:10;
y = 1:10;
plot(x, y);
Answer:
To change the color of a line in MATLAB, you can use the Color property. For example, the following command will change the color of the line to red:
x = 1:10;
y = 1:10;
plot(x, y, 'Color', 'red');
title
to a figure in MATLAB?Answer:
To add a title to a figure in MATLAB, you can use the title() function. For example, the following command will add the title “My Line Plot” to the figure:
x = 1:10;
y = 1:10;
plot(x, y);
title('My Line Plot');
Answer:
To add labels to the axes in a figure in MATLAB, you can use the xlabel() and ylabel() functions. For example, the following commands will add the labels “X-Axis” and “Y-Axis” to the x-axis and y-axis, respectively:
x = 1:10;
y = 1:10;
plot(x, y);
xlabel('X-Axis');
ylabel('Y-Axis');
Answer:
To add a grid to a figure in MATLAB, you can use the grid() function. For example, the following command will add a grid to the figure:
x = 1:10;
y = 1:10;
plot(x, y);
grid on;
Answer:
A 2D plot is used to visualize data that has two dimensions, such as height and weight. A 3D plot is used to visualize data that has three dimensions, such as height, weight, and depth.