bunch of gscatter with global legend in matlab

To create a scatter plot with multiple groups using gscatter in MATLAB and add a global legend, you can follow these steps:

  1. Create your data and assign a categorical variable for grouping. For example:
main.m
x = randn(100, 1);
y = randn(100, 1);
group = categorical(randi([1, 3], 100, 1), 1:3, {'Group 1', 'Group 2', 'Group 3'});
122 chars
4 lines
  1. Use the gscatter function to plot the data, specifying the variables for x and y, and the grouping variable:
main.m
gscatter(x, y, group)
22 chars
2 lines
  1. By default, gscatter generates a legend for each group. To create a global legend, you can remove the individual legends and create a new one using the legend function:
main.m
hFig = gcf; % Get the handle to the current figure
hLegend = legend('show'); % Create a default legend

% Delete the individual legends created by gscatter
hChild = findobj(hFig, 'Type', 'Legend');
delete(hChild)

% Customize the global legend as needed
set(hLegend, 'Location', 'best') % Adjust the location of the legend
323 chars
10 lines

That's it! You now have a scatter plot with multiple groups using gscatter and a global legend.

Note: If you have different markers or colors assigned to each group, you can specify them explicitly in the gscatter function call or use the optional input arguments to customize the appearance of the scatter plot.

related categories

gistlibby LogSnag