Problem with figure legend in loop for selecting multiple columns

2 Ansichten (letzte 30 Tage)
I am having difficulty with my legend displaying the correct colors for a loop plotting figure.
To trouble shoot, I have tried matrices and cell formats for my x and y variables. Both x and y contain 6 sets of 70x70 matrices. (So, for the matrix format, it becomes a 70x420 matrix)
Here the code works with the legend (where x and y are a 70x70 matrix)
N=6;
figure
hold on
clr = jet(N);
for j=1:N;
plot(x(1:end,j), y(1:end,j), 'Color',clr(j,:))
end
hold off
str = cellstr( num2str((1:N)','Run%d') );%
legend(str)
This creates a figure that displays different colors on the legend corresponding to the plot colors correctly
However, when I try to select various sets of columns in my 70x70 matrix in the x and y matrix, the legend colors become corrupt and display 4 blues and 2 cyan:
N=6;
figure
hold on
clr = jet(N);
for j=1:N;
plot(x(1:end,j:j+1), y(1:end,j:j+1), 'Color',clr(j,:))
end
hold off
str = cellstr( num2str((1:N)','Run%d') );%
legend(str)
Does anyone know how to fix the second image to correlate plot and legend colors? Why is it only when I try to select various columns?

Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 14 Aug. 2016
BYUBeetleGirl - looking closely at the colours in your second legend, there appears to be three distinct sets....which match the first three colours (or runs) in your first legend. The problem is because of
plot(x(1:end,j:j+1), y(1:end,j:j+1), 'Color',clr(j,:))
On each iteration of your for loop you are creating (I suspect) two plots and so two handles to two different graphics objects are being created. Consider the following
hObj = plot(rand(10,1),rand(10,1));
vs
hObjs = plot(rand(10,2),rand(10,2));
The former (like your first example) creates a handle to a single graphics object hObj, whereas the latter (like your second example) creates two handles to two graphics objects hObjs.
In your code, since the same colour is used for each pair and the legend is only interested in the first six graphics objects on your figure, then we will only see the first three colours.
I think that what you want to do is convert your matrices
x(1:end,j:j+1), y(1:end,j:j+1)
into arrays using reshape as
plot(reshape(x(1:end,j:j+1),[],1), reshape(y(1:end,j:j+1),[],1), 'Color',clr(j,:))
  1 Kommentar
Larz
Larz am 15 Aug. 2016
Thank you! This worked perfectly! I didn't realize there were 3 sets of colors until you pointed it out. I was trying to convert my matrices in some way, and this was it. I was originally hoping to use my data formatted as a cell as it is more compact, and this method works as well:
% plot(reshape(x{:,j},[],1),reshape(y{:,j},[],1),'Color',clr(j,:))
Thanks again!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by