Creating a Scatter Plot with a Trend Line in MATLAB Online

Julia Huang

Introduction

MATLAB Online is a powerful web-based tool for data analysis and visualization. It is especially useful when working with statistical data. If you have any needs for presenting relationships between variables, a scatter plot with a trend line is one of the most common and useful methods.

In this tutorial, I will show you step by step how to create a scatter plot and add a trend line using MATLAB Online.

Why Scatter Plots Matter

A scatter plot helps us understand the relationship between two variables. For example, it can show whether the data has a positive trend, negative trend, or no clear relationship.

Adding a trend line makes the pattern even clearer, which is why this method is widely used in data analysis, AI models, and statistical studies.

Step 1: Open MATLAB Online

Go to MATLAB Online in your browser and start a new script.

Step 2: Create Sample Data

x = 1:10;
y = 2*x + randn(1,10);

In this step, we generate sample data where y is approximately equal to 2x with some random noise. This simulates real-world data, which usually contains variation rather than being perfectly linear.

Step 3: Create the Scatter Plot

scatter(x, y);
title(‘Scatter Plot’);
xlabel(‘X’);
ylabel(‘Y’);
grid on;

In this step, we use the scatter function to visualize the relationship between x and y. We also add a title and axis labels to make the plot easier to understand. The grid is turned on to improve readability and make the data points clearer.

Step 4: Add a Trend Line

p = polyfit(x, y, 1);
yfit = polyval(p, x);
hold on;
plot(x, yfit, ‘r’);

In this step, we use polyfit to perform linear regression and find the best-fit line for the data. The polyval function is then used to calculate the predicted values. Finally, we plot the trend line on top of the scatter plot. The hold on command ensures that the line is added without removing the original data points.

Step 5: Final Result

Now you could see blue dots representing your data and a red line representing the trend. This clearly shows the relationship between the variables.

Why This Is Useful

This type of visualization is very common in data science, machine learning, AI model analysis, and business analytics. It helps people quickly understand patterns in data and make decisions.

Conclusion

We learned how to use MATLAB Online to create a scatter plot, add a trend line, and visualize relationships in data. Even with simple code, MATLAB can produce clear and professional visualizations.

Personal Note

I personally think this method is very useful because it appears frequently in real-world data analysis, especially in AI and statistics.

Liked it? Take a second to support Moore Statistics Consulting LLC on Patreon!
Become a patron at Patreon!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *