简体   繁体   中英

In MATLAB, how do I use legend with colormap in a scatter plot

In MATLAB, how do I use legend with colormap in a scatter plot?

For example:

colormap winter
xData = [1 2 3 4 5];
yData = [7 4 2 8 1];
col = [1 1 2 2 1];
h1 = scatter(xData, yData, 50, col,'s');
legend('one','two')

Obviously this legend is wrong as it only shows 'one'. I know that I could split up the data by col and plot two scatter plots but there must be a simple way of making a legend when using a colormap?

This is how I would plot the data using gscatter :

gscatter(xData,yData,col)
legend('one','two')

Obviously the output is optically not identical to scatter , but gscatter seems to be the right choice if you want to group your points by col

As an alternative solution, which preserves the scatter()-style i would suggest to to use scatter in a loop, one call for each of your groups. Therefore we create the colormap, which would be used and assign the colors manually:

xData = [1 2 3 4 5];
yData = [7 4 2 8 1];
col = [1 1 2 2 1];
groups = unique(col);
nGroups = length(groups);
cmap = colormap(winter(nGroups));
figure
hold on
for iGroup = 1:nGroups
    group = groups(iGroup);
    idx = col==group;
    scatter(xData(idx), yData(idx), 50, cmap(iGroup,:),'s');
end
legend('one','two')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM