Scatter Plot in MATLAB - GeeksforGeeks (2024)

Last Updated : 27 Oct, 2022

Improve

Improve

Like Article

Like

Save

Report

Scatter Plot is a popular type of graph plot that plots pairs of coordinate points discretely rather than continuously. These plots are extensively used in various industries such as the data science industry because of their statistical importance in visualizing vast datasets.

Scatter Plots in MATLAB:

MATLAB provides a power scatter() function to plot to scatter plots with many additional options.

Syntax:

scatter(x_data, y_data, <optional arguments>)

The x_data and y_data represent vectors of equal length which are used as x-coordinates and y-coordinates respectively. There are various optional arguments that we will see later on in this article. Now, let us understand the scatter function with the help of examples.

Plotting a simple vector x with y.

Example 1:

Matlab

% MATLAB code for scatter plot

% x_data

x = 23:75;

% y_data

y = 1:53;

% Plotting the scatter plot

scatter(x,y),xlabel("X"),ylabel("Y"),title("Scatter 1")

Output:

Scatter Plot in MATLAB - GeeksforGeeks (1)

A simple scatter plot

Here,

xlabel() gives the label to the horizontal axis.
ylabel() gives the label to the vertical axis.
title() gives the title to the graph

Now we will plot a scatter plot with variable sizes of circles.

Example 2:

Matlab

% MATLAB code for scatter plot

x = 23:75; %x_data

y = 1:53; %y_data

% Size vector of same size as x and y

csize = linspace(1,50,53);

% Plotting the scatter plot

scatter(x,y,csize),xlabel("X"),ylabel("Y"),title("Scatter 1")

Output:

Here, the csize vector specifies the size for each circle in the same order as x and y. You can also use a scalar size for each circle or a vector as in the above example for variable size.

We can also have different colors for the circles. See the below implementation.

Example 3:

Matlab

% MATLAB code

x = linspace(-pi,pi,100); %x_data

y = cos(x).^2; %y_data

% Color vector of same size as x and y

col = linspace(1,7,length(x));

% Plotting the scatter plot

scatter(x,y,5,col),xlabel("X"),ylabel("Y"),title("Scatter 1")

Output:

Scatter Plot in MATLAB - GeeksforGeeks (3)

Here, we are plotting the cos2(x) function in [-pi, pi] domain. The “col” vector specifies the vector which stores the RGB value for each circle and we have used the fixed size 5, for each circle.

Note: It is necessary to specify the circle size before the color argument due to the syntax of the scatter command. In case you want it to be the default, put an empty vector [] instead of 5 in the above example.

We can also plot two columns of a table at a time.

Example 4:

Matlab

% MATLAB code scatter plot

x = linspace(-3,3,73);

y = x.^3;

% Creating table from x and y vectors

tbe = table(x,y);

% Plotting the scatter plot from table tbe

scatter(tbe,"x","y",'filled'),xlabel("X Column"),

ylabel("Y Column"),title("Scatter From Table")

Output:

Scatter Plot in MATLAB - GeeksforGeeks (4)

In this example, we scatter plot the two columns of the table tbe with filled circles.



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Scatter Plot in MATLAB - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6502

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.