MATLAB Plotting

This chapter introduces Plotting in MATLAB, a powerful feature for visualizing data in various formats, including 2D and 3D plots. MATLAB’s plotting tools enable users to create detailed, customizable visualizations to analyze and present data effectively. By mastering MATLAB plotting, users can turn raw data into insightful graphics.

Chapter Goal

The goal of this chapter is to provide a comprehensive understanding of MATLAB plotting features, focusing on:

  1. Learning the basic syntax for creating 2D and 3D plots.
  2. Exploring plot customization options like titles, labels, legends, and colors.
  3. Understanding advanced plotting techniques for specialized data visualization.
  4. Implementing best practices for clear and effective plots.

Key Characteristics for MATLAB Plotting

  1. Wide Range of Plot Types: MATLAB supports line plots, scatter plots, bar charts, histograms, surface plots, and more.
  2. Highly Customizable: Users can adjust plot aesthetics such as colors, line styles, markers, and annotations.
  3. Interactive Features: Zooming, panning, and data tips enhance the exploration of plotted data.
  4. Built-in Functions: MATLAB includes built-in plotting functions like plot, bar, scatter, and surf for quick visualizations.
  5. Integration with Data: MATLAB plots seamlessly integrate with its data processing and analysis capabilities.

Basic Rules for MATLAB Plotting

  1. Use Appropriate Plot Types: Match the plot type to the nature of your data for effective visualization.
  2. Label Axes and Add Titles: Always include descriptive labels and a title to provide context for the plot.
  3. Customize Legends: Use legends to explain multiple datasets plotted on the same graph.
  4. Limit Overcrowding: Avoid cluttered plots by limiting the number of data series or annotations.
  5. Save Plots: Export plots to image formats (.png, .jpg) or vector formats (.pdf, .eps) for sharing and publishing.

Best Practices

  1. Focus on Clarity: Ensure plots are easy to understand with clear labels, legends, and annotations.
  2. Use Consistent Styles: Apply consistent colors, line styles, and fonts across multiple plots for uniformity.
  3. Combine Plots Thoughtfully: Use subplots or overlay multiple datasets when comparisons are necessary.
  4. Test Different Perspectives: Experiment with 3D views and data slicing to reveal hidden patterns.
  5. Document Plot Code: Include comments in your script explaining the purpose and structure of each plot.

This chapter equips you with the knowledge to create compelling visualizations in MATLAB, enabling effective communication of data insights. Subsequent sections will delve into syntax, examples, and real-world applications.

Syntax Table

Serial No Component Syntax Example Description
1 Line Plot plot(x, y) Creates a 2D line plot of y versus x.
2 Scatter Plot scatter(x, y) Creates a scatter plot of points with coordinates defined by x and y.
3 Bar Chart bar(x, y) Creates a bar chart with categories x and values y.
4 Histogram histogram(data) Displays a histogram of the input data.
5 Surface Plot surf(X, Y, Z) Creates a 3D surface plot using matrices X, Y, and Z.

Syntax Explanation

1. Line Plot

What is a Line Plot?

A line plot displays data points connected by a continuous line, often used for trends.

Syntax:

plot(x, y);

Detailed Explanation:

  • x and y are arrays of the same length.
  • Each point (x(i), y(i)) is connected by a line segment.

Example:

x = 0:0.1:10;

y = sin(x);

plot(x, y);

title(‘Sine Wave’);

xlabel(‘x’);

ylabel(‘sin(x)’);

Output:

A 2D line plot of sin(x) versus x.

2. Scatter Plot

What is a Scatter Plot?

A scatter plot displays individual data points without connecting lines, useful for correlations.

Syntax:

scatter(x, y);

Detailed Explanation:

  • x and y are arrays of the same length.
  • Points are plotted as unconnected markers.

Example:

x = rand(1, 10);

y = rand(1, 10);

scatter(x, y);

title(‘Random Scatter Plot’);

xlabel(‘x’);

ylabel(‘y’);

Output:

A scatter plot with random points.

3. Bar Chart

What is a Bar Chart?

A bar chart displays categorical data with bars proportional to values.

Syntax:

bar(x, y);

Detailed Explanation:

  • x contains categories, y contains corresponding values.

Example:

categories = {‘A’, ‘B’, ‘C’};

values = [10, 20, 15];

bar(categorical(categories), values);

title(‘Category Values’);

xlabel(‘Category’);

ylabel(‘Values’);

Output:

A bar chart showing values for categories A, B, and C.

4. Histogram

What is a Histogram?

A histogram displays the distribution of data across bins.

Syntax:

histogram(data);

Detailed Explanation:

  • Data is divided into bins, and the count for each bin is displayed as bars.

Example:

data = randn(1, 1000);

histogram(data);

title(‘Data Distribution’);

xlabel(‘Value’);

ylabel(‘Frequency’);

Output:

A histogram showing the frequency distribution of data.

5. Surface Plot

What is a Surface Plot?

A surface plot displays a 3D surface defined by matrices X, Y, and Z.

Syntax:

surf(X, Y, Z);

Detailed Explanation:

  • X, Y define the grid, Z defines the surface height at each grid point.

Example:

[X, Y] = meshgrid(-5:0.5:5, -5:0.5:5);

Z = sin(sqrt(X.^2 + Y.^2));

surf(X, Y, Z);

title(‘3D Surface Plot’);

xlabel(‘X-axis’);

ylabel(‘Y-axis’);

zlabel(‘Z-axis’);

Output:

A 3D surface plot based on the function sin(sqrt(X^2 + Y^2)).

Notes

  • Always choose the plot type that best represents your data.
  • Use labels, titles, and legends for clear communication.

Warnings

  • Ensure input arrays have compatible dimensions.
  • Overlapping data series without differentiation can lead to misleading plots.

Real-Life Project: Sales Performance Visualization

Project Name: Weekly Sales Analysis

Project Goal:

To use MATLAB plotting functions to visualize weekly sales data and identify trends, enabling better decision-making.

Steps in the Project:

  1. Define the Data:
    • Create arrays for weekly sales data and product categories.
  2. Generate Plots:
    • Use a line plot to show trends in weekly sales.
    • Use a bar chart to compare sales across product categories.
  3. Customize Plots:
    • Add labels, titles, legends, and grid lines for clarity.

Code for This Project:

% Step 1: Define the data

weeks = 1:10;

sales = [500, 700, 800, 600, 900, 1000, 1100, 950, 850, 1200];

products = {‘Product A’, ‘Product B’, ‘Product C’};

productSales = [300, 400, 200; 350, 450, 250; 400, 500, 300; 450, 550, 350; 500, 600, 400; 

                550, 650, 450; 600, 700, 500; 650, 750, 550; 700, 800, 600; 750, 850, 650];

 

% Step 2: Generate plots

figure;

subplot(2, 1, 1);

plot(weeks, sales, ‘-o’);

title(‘Weekly Sales Trend’);

xlabel(‘Week’);

ylabel(‘Total Sales’);

grid on;

 

subplot(2, 1, 2);

bar(categorical(products), sum(productSales, 1));

title(‘Sales by Product Category’);

xlabel(‘Product’);

ylabel(‘Total Sales’);

grid on;

Save and Run:

  1. Save the script as sales_analysis.m.
  2. Run the script in MATLAB.

Expected Output:

  1. Line Plot:
    • A line plot showing total sales trends over 10 weeks.
  2. Bar Chart:
    • A bar chart displaying total sales for each product category.

Learning Outcomes:

  • Learn to create and customize multiple plot types in MATLAB.
  • Understand how to visualize trends and compare categories.
  • Gain insights into applying MATLAB plotting for real-world data analysis.