In a for loop using gscatter, how do I fix the legend entries to be the same in all graphics?

7 views (last 30 days)
Hi,
I have been having trouble figuring how to use the legend properly in a loop for, using gscatter.
I have to graph 52 weeks, and I have a variable group containing value from 1 to 6. However, in some weeks, some of the grouping frequency is zero. The legend is not reflecting properly the right group.
for Example, on the week no 4, this is the frequency in my group:
Value Count Percent
1 0 0.00%
2 0 0.00%
3 12 1.45%
4 408 49.22%
5 403 48.61%
6 6 0.72%
However, Matlab doesn't keep all the legend entries and change the color. It displays Group 1,2,3,4 instead of 3,4,5,6.
How can I fix this? Is there a way I can make my own homemade legend so that it is the same for each graph (I need 6 labels in the legend, reprensenting my 6 groups, and keeping the same color all the way).
Here is my code, to help you understand:
for i = 1:52
idx = Week == i;
thisVariables= variables (idx, :);
thisCavitation = thisVariables(:,1);
thisMW = thisVariables(:,2);
thisGroup = thisVariables(:,3);
figure
set(gcf,'Position',[60 502 1000 220])
% plot MW vs Cavitation for one week
subplot(1,3,1)
set(gca, 'Position', [0.23 0.2 0.18 0.65])
g1 = gscatter(thisMW, thisCavitation, thisGroup,'rygcbm',[],12);
title('Cavitation vs MW', 'FontSize',12)
xlabel( 'MW')
ylabel ('Cavitation ')
legend1 = legend('Zone 1,'Zone 2', 'Zone 3,'Zone 4, Zone 5,'Zone 6',-1);
set(legend1,'Position',[0.02 0.7 0.15 0.1])
end
Is there a way to understand how Matlab assign group to color and legend entry?
Thank you for your help!
  1 Comment
Miro
Miro on 19 Jul 2012
i guess, that in some positions of your loop, there is no data available to be plotted. If this is the case, the legend is shifted. So what you probably have to do is to check the values that are being plotted before plotting them.

Sign in to comment.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!