MATLAB - Graphics
MATLAB - Advanced Graphics and Visualization
Section titled “MATLAB - Advanced Graphics and Visualization”MATLAB offers a powerful and flexible graphics system for visualizing data. This chapter explores how to create common plot types and customize them to produce publication-quality figures.
- Creating bar charts for categorical data
- Visualizing 3D data with contour plots
- Generating 3D surface and mesh plots
- Modern techniques for creating high-quality graphics
Drawing Bar Charts
Section titled “Drawing Bar Charts”The bar function is ideal for displaying quantities associated with different categories. Let’s visualize the test scores of a group of students.
Example
Section titled “Example”This script will generate a bar chart of student scores and save it as a high-resolution image file.
% Data: Student scoresstudent_ids = 1:10;scores = [75, 58, 90, 87, 50, 85, 92, 75, 60, 95];
% Create the figurefigure;
% Draw the bar chart with custom colorb = bar(student_ids, scores, 'FaceColor', [0.2, 0.6, 0.8]);
% Add labels and title for clarityxlabel('Student ID');ylabel('Score (%)');title('First Semester Exam Scores');grid on; % Add a grid for better readabilityylim([0 100]); % Set y-axis limits
% Save the figure to a file% exportgraphics is the modern, recommended function for saving plotsexportgraphics(gcf, 'student_scores.png', 'Resolution', 300);
% To run this, save the code in a .m file and execute it.% A plot window will appear, and a file named 'student_scores.png' will be saved.The code will produce a window with a bar chart showing ten bars, each corresponding to a student’s score. The x-axis is labeled ‘Student ID’, the y-axis is ‘Score (%)’, and the chart has a title. The bars are colored blue and a grid is visible in the background. A PNG file of this chart is also created.
Drawing Contour Plots
Section titled “Drawing Contour Plots”A contour plot is a 2D representation of a 3D surface. It uses lines or filled areas to connect points of equal value (level). It’s like a topographical map for data.
Example
Section titled “Example”To create a contour plot, we first need to define a grid of (x, y) points using meshgrid, then evaluate a function z = f(x, y) at each point on the grid.
% Step 1: Create a grid of X and Y coordinates[X, Y] = meshgrid(-2:0.2:2, -2:0.2:2);
% Step 2: Define the function Z = f(X, Y)Z = X .* exp(-X.^2 - Y.^2);
% Step 3: Create the contour plotfigure;[C, h] = contour(X, Y, Z, 10); % Create a contour plot with 10 levels
% Step 4: Add labels to the contour linesclabel(C, h);
% Add title and axis labelstitle('Contour Plot of Z = X*exp(-X^2 - Y^2)');xlabel('X-axis');ylabel('Y-axis');
% Save the figureexportgraphics(gcf, 'contour_plot.png', 'Resolution', 300);This script generates a 2D plot with a series of concentric, oval-shaped lines. Each line is labeled with a number representing its constant Z-value. This shows the ‘hills’ and ‘valleys’ of the 3D function on a flat plane.
Three-Dimensional Plots
Section titled “Three-Dimensional Plots”For a true 3D view of a surface z = f(x, y), MATLAB provides functions like surf and mesh.
surf: Creates a 3D surface plot with solid colored faces.
mesh: Creates a 3D wireframe mesh plot.
Example
Section titled “Example”% Reuse the grid and function from the contour example[X, Y] = meshgrid(-2:0.2:2);Z = X .* exp(-X.^2 - Y.^2);
% Create a new figurefigure;
% Use 'tiledlayout' to show multiple plots in one figuretiledlayout(1, 2); % 1 row, 2 columns
% First tile: surf plotnexttile;surf(X, Y, Z);shading interp; % Smooths the color gradientcolormap('winter'); % Apply a color schemetitle('surf() plot');xlabel('x'); ylabel('y'); zlabel('z');
% Second tile: mesh plotnexttile;mesh(X, Y, Z);title('mesh() plot');xlabel('x'); ylabel('y'); zlabel('z');
% Save the combined figureexportgraphics(gcf, '3d_plots.png', 'Resolution', 300);This code produces a single figure window containing two plots side-by-side. The left plot (surf) shows a smooth, colored surface representing the function, with one peak and one valley. The right plot (mesh) shows the same surface but as a wireframe, allowing you to see through it. This demonstrates the modern tiledlayout function for arranging subplots.
Best Practices for Publication-Quality Graphics
Section titled “Best Practices for Publication-Quality Graphics”- Always Label: Every plot needs a title, and every axis needs a label with units (
xlabel,ylabel,zlabel). - Use Handles: Get handles to plot objects to programmatically control their properties (e.g.,
ax = gca; ax.FontSize = 12;). This offers more control than simple commands. - Choose Appropriate Colormaps: Use colormaps that are intuitive and accessible (e.g., perceptually uniform colormaps like ‘viridis’ or ‘parula’).
tiledlayoutoversubplot: For new code, prefertiledlayoutfor arranging multiple plots. It provides better spacing and more intuitive controls.- Export with
exportgraphics: Useexportgraphicsinstead of the olderprintcommand. It offers better control over resolution, file formats (PNG, JPEG, PDF, EPS), and background color.